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-agent/src/main/java/org/apache/helix
|
Create_ds/helix/helix-agent/src/main/java/org/apache/helix/agent/CommandConfig.java
|
package org.apache.helix.agent;
/*
* 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.TreeMap;
public class CommandConfig {
private final String _fromState;
private final String _toState;
private final String _command;
private final String _workingDir;
private final String _timeout;
private final String _pidFile;
public CommandConfig(String fromState, String toState, String command, String workingDir,
String timeout, String pidFile) {
if (command == null) {
throw new IllegalArgumentException("command is null");
}
_fromState = fromState;
_toState = toState;
_command = command;
_workingDir = workingDir;
_timeout = timeout;
_pidFile = pidFile;
}
private String buildKey(String fromState, String toState, CommandAttribute attribute) {
return fromState + "-" + toState + "." + attribute.getName();
}
public Map<String, String> toKeyValueMap() {
Map<String, String> map = new TreeMap<String, String>();
map.put(buildKey(_fromState, _toState, CommandAttribute.COMMAND), _command);
if (!_command.equals(CommandAttribute.NOP.getName())) {
if (_workingDir != null) {
map.put(buildKey(_fromState, _toState, CommandAttribute.WORKING_DIR), _workingDir);
}
if (_timeout != null) {
map.put(buildKey(_fromState, _toState, CommandAttribute.TIMEOUT), _timeout);
}
if (_pidFile != null) {
map.put(buildKey(_fromState, _toState, CommandAttribute.PID_FILE), _pidFile);
}
}
return map;
}
/**
* builder for command-config
*/
public static class Builder {
private String _fromState;
private String _toState;
private String _command;
private String _workingDir;
private String _timeout;
private String _pidFile;
public Builder setTransition(String fromState, String toState) {
_fromState = fromState;
_toState = toState;
return this;
}
public Builder setCommand(String command) {
_command = command;
return this;
}
public Builder setCommandWorkingDir(String workingDir) {
_workingDir = workingDir;
return this;
}
public Builder setCommandTimeout(String timeout) {
_timeout = timeout;
return this;
}
public Builder setPidFile(String pidFile) {
_pidFile = pidFile;
return this;
}
public CommandConfig build() {
return new CommandConfig(_fromState, _toState, _command, _workingDir, _timeout, _pidFile);
}
}
}
| 9,400 |
0 |
Create_ds/helix/helix-agent/src/main/java/org/apache/helix
|
Create_ds/helix/helix-agent/src/main/java/org/apache/helix/agent/CommandAttribute.java
|
package org.apache.helix.agent;
/*
* 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;
public enum CommandAttribute {
COMMAND("command"),
WORKING_DIR("command.workingDir"),
TIMEOUT("command.timeout"),
PID_FILE("command.pidFile"),
NOP("nop");
// map from name to value
private static final Map<String, CommandAttribute> map = new HashMap<String, CommandAttribute>();
static {
for (CommandAttribute attr : CommandAttribute.values()) {
map.put(attr.getName(), attr);
}
}
private final String _name;
private CommandAttribute(String name) {
_name = name;
}
public String getName() {
return _name;
}
public static CommandAttribute getCommandAttributeByName(String name) {
return map.get(name);
}
}
| 9,401 |
0 |
Create_ds/helix/helix-agent/src/main/java/org/apache/helix
|
Create_ds/helix/helix-agent/src/main/java/org/apache/helix/agent/ProcessMonitorThread.java
|
package org.apache.helix.agent;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.helix.agent.SystemUtil.ProcessStateCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* 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.
*/
/**
* thread for monitoring a pid
*/
public class ProcessMonitorThread extends Thread {
private static final Logger LOG = LoggerFactory.getLogger(ProcessMonitorThread.class);
private static final int MONITOR_PERIOD_BASE = 1000; // 1 second
private final String _pid;
public ProcessMonitorThread(String pid) {
_pid = pid;
}
@Override
public void run() {
// monitor pid
try {
ProcessStateCode processState = SystemUtil.getProcessState(_pid);
while (processState != null) {
if (processState == ProcessStateCode.Z) {
LOG.error("process: " + _pid + " is in zombie state");
break;
}
TimeUnit.MILLISECONDS
.sleep(new Random().nextInt(MONITOR_PERIOD_BASE) + MONITOR_PERIOD_BASE);
processState = SystemUtil.getProcessState(_pid);
}
} catch (Exception e) {
LOG.error("fail to monitor process: " + _pid, e);
}
// TODO need to find the exit value of pid and kill the pid on timeout
}
}
| 9,402 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestHelper.java
|
package org.apache.helix;
/*
* 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.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.RebalanceStrategy;
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.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.model.StateModelDefinition.StateModelDefinitionProperty;
import org.apache.helix.store.zk.ZNode;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.util.ZKClientPool;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory;
import org.apache.helix.zookeeper.zkclient.IDefaultNameSpace;
import org.apache.helix.zookeeper.zkclient.IZkChildListener;
import org.apache.helix.zookeeper.zkclient.IZkDataListener;
import org.apache.helix.zookeeper.zkclient.ZkClient;
import org.apache.helix.zookeeper.zkclient.ZkServer;
import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
public class TestHelper {
private static final Logger LOG = LoggerFactory.getLogger(TestHelper.class);
public static final long WAIT_DURATION = 60 * 1000L; // 60 seconds
public static final int DEFAULT_REBALANCE_PROCESSING_WAIT_TIME = 1500;
/**
* Returns a unused random port.
*/
public static int getRandomPort() throws IOException {
ServerSocket sock = new ServerSocket();
sock.bind(null);
int port = sock.getLocalPort();
sock.close();
return port;
}
static public ZkServer startZkServer(final String zkAddress) throws Exception {
List<String> empty = Collections.emptyList();
return TestHelper.startZkServer(zkAddress, empty, true);
}
static public ZkServer startZkServer(final String zkAddress, final String rootNamespace)
throws Exception {
List<String> rootNamespaces = new ArrayList<String>();
rootNamespaces.add(rootNamespace);
return TestHelper.startZkServer(zkAddress, rootNamespaces, true);
}
static public ZkServer startZkServer(final String zkAddress, final List<String> rootNamespaces)
throws Exception {
return startZkServer(zkAddress, rootNamespaces, true);
}
static public ZkServer startZkServer(final String zkAddress, final List<String> rootNamespaces,
boolean overwrite) throws Exception {
System.out.println(
"Start zookeeper at " + zkAddress + " in thread " + Thread.currentThread().getName());
String zkDir = zkAddress.replace(':', '_');
final String logDir = "/tmp/" + zkDir + "/logs";
final String dataDir = "/tmp/" + zkDir + "/dataDir";
if (overwrite) {
FileUtils.deleteDirectory(new File(dataDir));
FileUtils.deleteDirectory(new File(logDir));
}
ZKClientPool.reset();
IDefaultNameSpace defaultNameSpace = new IDefaultNameSpace() {
@Override
public void createDefaultNameSpace(ZkClient zkClient) {
if (rootNamespaces == null) {
return;
}
for (String rootNamespace : rootNamespaces) {
try {
zkClient.deleteRecursive(rootNamespace);
} catch (Exception e) {
LOG.error("fail to deleteRecursive path:" + rootNamespace, e);
}
}
}
};
int port = Integer.parseInt(zkAddress.substring(zkAddress.lastIndexOf(':') + 1));
ZkServer zkServer = new ZkServer(dataDir, logDir, defaultNameSpace, port);
zkServer.start();
return zkServer;
}
static public void stopZkServer(ZkServer zkServer) {
if (zkServer != null) {
zkServer.shutdown();
System.out.println(
"Shut down zookeeper at port " + zkServer.getPort() + " in thread " + Thread
.currentThread().getName());
}
}
public static void setupEmptyCluster(HelixZkClient zkClient, String clusterName) {
ZKHelixAdmin admin = new ZKHelixAdmin(zkClient);
admin.addCluster(clusterName, true);
}
/**
* convert T[] to set<T>
* @param s
* @return
*/
public static <T> Set<T> setOf(T... s) {
Set<T> set = new HashSet<T>(Arrays.asList(s));
return set;
}
/**
* generic method for verification with a timeout
* @param verifierName
* @param args
*/
public static void verifyWithTimeout(String verifierName, long timeout, Object... args) {
final long sleepInterval = 1000; // in ms
final int loop = (int) (timeout / sleepInterval) + 1;
try {
boolean result = false;
int i = 0;
for (; i < loop; i++) {
Thread.sleep(sleepInterval);
// verifier should be static method
result = (Boolean) TestHelper.getMethod(verifierName).invoke(null, args);
if (result == true) {
break;
}
}
// debug
// LOG.info(verifierName + ": wait " + ((i + 1) * 1000) + "ms to verify ("
// + result + ")");
System.err.println(
verifierName + ": wait " + ((i + 1) * 1000) + "ms to verify " + " (" + result + ")");
LOG.debug("args:" + Arrays.toString(args));
// System.err.println("args:" + Arrays.toString(args));
if (result == false) {
LOG.error(verifierName + " fails");
LOG.error("args:" + Arrays.toString(args));
}
Assert.assertTrue(result);
} catch (Exception e) {
LOG.error("Exception in verify: " + verifierName, e);
}
}
private static Method getMethod(String name) {
Method[] methods = TestHelper.class.getMethods();
for (Method method : methods) {
if (name.equals(method.getName())) {
return method;
}
}
return null;
}
public static boolean verifyEmptyCurStateAndExtView(String clusterName, String resourceName,
Set<String> instanceNames, String zkAddr) {
HelixZkClient zkClient = SharedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddr));
zkClient.setZkSerializer(new ZNRecordSerializer());
try {
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient));
Builder keyBuilder = accessor.keyBuilder();
for (String instanceName : instanceNames) {
List<String> sessionIds = accessor.getChildNames(keyBuilder.sessions(instanceName));
for (String sessionId : sessionIds) {
CurrentState curState =
accessor.getProperty(keyBuilder.currentState(instanceName, sessionId, resourceName));
if (curState != null && curState.getRecord().getMapFields().size() != 0) {
return false;
}
CurrentState taskCurState =
accessor.getProperty(keyBuilder.taskCurrentState(instanceName, sessionId, resourceName));
if (taskCurState != null && taskCurState.getRecord().getMapFields().size() != 0) {
return false;
}
}
ExternalView extView = accessor.getProperty(keyBuilder.externalView(resourceName));
if (extView != null && extView.getRecord().getMapFields().size() != 0) {
return false;
}
}
return true;
} finally {
zkClient.close();
}
}
public static boolean verifyNotConnected(HelixManager manager) {
return !manager.isConnected();
}
public 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 {
TestHelper
.setupCluster(clusterName, zkAddr, startPort, participantNamePrefix, resourceNamePrefix,
resourceNb, partitionNb, nodesNb, replica, stateModelDef, RebalanceMode.SEMI_AUTO,
doRebalance);
}
public static void setupCluster(String clusterName, String zkAddr, int startPort,
String participantNamePrefix, String resourceNamePrefix, int resourceNb, int partitionNb,
int nodesNb, int replica, String stateModelDef, RebalanceMode mode, boolean doRebalance) {
HelixZkClient zkClient = SharedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddr));
try {
if (zkClient.exists("/" + clusterName)) {
LOG.warn("Cluster already exists:" + clusterName + ". Deleting it");
zkClient.deleteRecursively("/" + clusterName);
}
ClusterSetup setupTool = new ClusterSetup(zkAddr);
setupTool.addCluster(clusterName, true);
for (int i = 0; i < nodesNb; i++) {
int port = startPort + i;
setupTool.addInstanceToCluster(clusterName, participantNamePrefix + "_" + port);
}
for (int i = 0; i < resourceNb; i++) {
String resourceName = resourceNamePrefix + i;
setupTool.addResourceToCluster(clusterName, resourceName, partitionNb, stateModelDef,
mode.name(),
mode == RebalanceMode.FULL_AUTO ? CrushEdRebalanceStrategy.class.getName()
: RebalanceStrategy.DEFAULT_REBALANCE_STRATEGY);
if (doRebalance) {
setupTool.rebalanceStorageCluster(clusterName, resourceName, replica);
}
}
} finally {
zkClient.close();
}
}
public static void dropCluster(String clusterName, RealmAwareZkClient zkClient) {
ClusterSetup setupTool = new ClusterSetup(zkClient);
dropCluster(clusterName, zkClient, setupTool);
}
public static void dropCluster(String clusterName, RealmAwareZkClient zkClient, ClusterSetup setup) {
String namespace = "/" + clusterName;
if (zkClient.exists(namespace)) {
try {
setup.deleteCluster(clusterName);
} catch (Exception ex) {
// Failed to delete, give some more time for connections to drop
try {
Thread.sleep(3000L);
setup.deleteCluster(clusterName);
} catch (Exception ignored) {
// OK - just ignore
}
}
}
}
/**
* @param stateMap
* : "ResourceName/partitionKey" -> setOf(instances)
* @param state
* : MASTER|SLAVE|ERROR...
*/
public static void verifyState(String clusterName, String zkAddr,
Map<String, Set<String>> stateMap, String state) {
HelixZkClient zkClient = SharedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddr));
zkClient.setZkSerializer(new ZNRecordSerializer());
try {
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient));
Builder keyBuilder = accessor.keyBuilder();
for (String resGroupPartitionKey : stateMap.keySet()) {
Map<String, String> retMap = getResourceAndPartitionKey(resGroupPartitionKey);
String resGroup = retMap.get("RESOURCE");
String partitionKey = retMap.get("PARTITION");
ExternalView extView = accessor.getProperty(keyBuilder.externalView(resGroup));
for (String instance : stateMap.get(resGroupPartitionKey)) {
String actualState = extView.getStateMap(partitionKey).get(instance);
Assert.assertNotNull(actualState,
"externalView doesn't contain state for " + resGroup + "/" + partitionKey + " on "
+ instance + " (expect " + state + ")");
Assert.assertEquals(actualState, state,
"externalView for " + resGroup + "/" + partitionKey + " on " + instance + " is "
+ actualState + " (expect " + state + ")");
}
}
} finally {
zkClient.close();
}
}
/**
* @param resourcePartition
* : key is in form of "resource/partitionKey" or "resource_x"
* @return
*/
private static Map<String, String> getResourceAndPartitionKey(String resourcePartition) {
String resourceName;
String partitionName;
int idx = resourcePartition.indexOf('/');
if (idx > -1) {
resourceName = resourcePartition.substring(0, idx);
partitionName = resourcePartition.substring(idx + 1);
} else {
idx = resourcePartition.lastIndexOf('_');
resourceName = resourcePartition.substring(0, idx);
partitionName = resourcePartition;
}
Map<String, String> retMap = new HashMap<String, String>();
retMap.put("RESOURCE", resourceName);
retMap.put("PARTITION", partitionName);
return retMap;
}
public static <T> Map<String, T> startThreadsConcurrently(final int nrThreads,
final Callable<T> method, final long timeout) {
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch finishCounter = new CountDownLatch(nrThreads);
final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>();
final List<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < nrThreads; i++) {
Thread thread = new Thread() {
@Override
public void run() {
try {
boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS);
if (isTimeout) {
LOG.error("Timeout while waiting for start latch");
}
} catch (InterruptedException ex) {
LOG.error("Interrupted while waiting for start latch");
}
try {
T result = method.call();
if (result != null) {
resultsMap.put("thread_" + this.getId(), result);
}
LOG.debug("result=" + result);
} catch (Exception e) {
LOG.error("Exeption in executing " + method.getClass().getName(), e);
}
finishCounter.countDown();
}
};
threadList.add(thread);
thread.start();
}
startLatch.countDown();
// wait for all thread to complete
try {
boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS);
if (isTimeout) {
LOG.error("Timeout while waiting for finish latch. Interrupt all threads");
for (Thread thread : threadList) {
thread.interrupt();
}
}
} catch (InterruptedException e) {
LOG.error("Interrupted while waiting for finish latch", e);
}
return resultsMap;
}
public static Message createMessage(String msgId, String fromState, String toState,
String tgtName, String resourceName, String partitionName) {
Message msg = new Message(MessageType.STATE_TRANSITION, msgId);
msg.setFromState(fromState);
msg.setToState(toState);
msg.setTgtName(tgtName);
msg.setResourceName(resourceName);
msg.setPartitionName(partitionName);
msg.setStateModelDef("MasterSlave");
return msg;
}
public static String getTestMethodName() {
StackTraceElement[] calls = Thread.currentThread().getStackTrace();
return calls[2].getMethodName();
}
public static String getTestClassName() {
StackTraceElement[] calls = Thread.currentThread().getStackTrace();
String fullClassName = calls[2].getClassName();
return fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
}
public static <T> Map<String, T> startThreadsConcurrently(final List<Callable<T>> methods,
final long timeout) {
final int nrThreads = methods.size();
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch finishCounter = new CountDownLatch(nrThreads);
final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>();
final List<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < nrThreads; i++) {
final Callable<T> method = methods.get(i);
Thread thread = new Thread() {
@Override
public void run() {
try {
boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS);
if (isTimeout) {
LOG.error("Timeout while waiting for start latch");
}
} catch (InterruptedException ex) {
LOG.error("Interrupted while waiting for start latch");
}
try {
T result = method.call();
if (result != null) {
resultsMap.put("thread_" + this.getId(), result);
}
LOG.debug("result=" + result);
} catch (Exception e) {
LOG.error("Exeption in executing " + method.getClass().getName(), e);
}
finishCounter.countDown();
}
};
threadList.add(thread);
thread.start();
}
startLatch.countDown();
// wait for all thread to complete
try {
boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS);
if (isTimeout) {
LOG.error("Timeout while waiting for finish latch. Interrupt all threads");
for (Thread thread : threadList) {
thread.interrupt();
}
}
} catch (InterruptedException e) {
LOG.error("Interrupted while waiting for finish latch", e);
}
return resultsMap;
}
public static void printCache(Map<String, ZNode> cache) {
System.out.println("START:Print cache");
TreeMap<String, ZNode> map = new TreeMap<String, ZNode>();
map.putAll(cache);
for (String key : map.keySet()) {
ZNode node = map.get(key);
TreeSet<String> childSet = new TreeSet<String>();
childSet.addAll(node.getChildSet());
System.out.print(
key + "=" + node.getData() + ", " + childSet + ", " + (node.getStat() == null ? "null\n"
: node.getStat()));
}
System.out.println("END:Print cache");
}
public static void readZkRecursive(String path, Map<String, ZNode> map, HelixZkClient zkclient) {
try {
Stat stat = new Stat();
ZNRecord record = zkclient.readData(path, stat);
List<String> childNames = zkclient.getChildren(path);
ZNode node = new ZNode(path, record, stat);
node.addChildren(childNames);
map.put(path, node);
for (String childName : childNames) {
String childPath = path + "/" + childName;
readZkRecursive(childPath, map, zkclient);
}
} catch (ZkNoNodeException e) {
// OK
}
}
public static void readZkRecursive(String path, Map<String, ZNode> map,
BaseDataAccessor<ZNRecord> zkAccessor) {
try {
Stat stat = new Stat();
ZNRecord record = zkAccessor.get(path, stat, 0);
List<String> childNames = zkAccessor.getChildNames(path, 0);
// System.out.println("childNames: " + childNames);
ZNode node = new ZNode(path, record, stat);
node.addChildren(childNames);
map.put(path, node);
if (childNames != null && !childNames.isEmpty()) {
for (String childName : childNames) {
String childPath = path + "/" + childName;
readZkRecursive(childPath, map, zkAccessor);
}
}
} catch (ZkNoNodeException e) {
// OK
}
}
public static boolean verifyZkCache(List<String> paths, BaseDataAccessor<ZNRecord> zkAccessor,
HelixZkClient zkclient, boolean needVerifyStat) {
// read everything
Map<String, ZNode> zkMap = new HashMap<String, ZNode>();
Map<String, ZNode> cache = new HashMap<String, ZNode>();
for (String path : paths) {
readZkRecursive(path, zkMap, zkclient);
readZkRecursive(path, cache, zkAccessor);
}
// printCache(map);
return verifyZkCache(paths, null, cache, zkMap, needVerifyStat);
}
public static boolean verifyZkCache(List<String> paths, Map<String, ZNode> cache,
HelixZkClient zkclient, boolean needVerifyStat) {
return verifyZkCache(paths, null, cache, zkclient, needVerifyStat);
}
public static boolean verifyZkCache(List<String> paths, List<String> pathsExcludeForStat,
Map<String, ZNode> cache, HelixZkClient zkclient, boolean needVerifyStat) {
// read everything on zk under paths
Map<String, ZNode> zkMap = new HashMap<String, ZNode>();
for (String path : paths) {
readZkRecursive(path, zkMap, zkclient);
}
// printCache(map);
return verifyZkCache(paths, pathsExcludeForStat, cache, zkMap, needVerifyStat);
}
public static boolean verifyZkCache(List<String> paths, List<String> pathsExcludeForStat,
Map<String, ZNode> cache, Map<String, ZNode> zkMap, boolean needVerifyStat) {
// equal size
if (zkMap.size() != cache.size()) {
System.err
.println("size mismatch: cacheSize: " + cache.size() + ", zkMapSize: " + zkMap.size());
System.out.println("cache: (" + cache.size() + ")");
TestHelper.printCache(cache);
System.out.println("zkMap: (" + zkMap.size() + ")");
TestHelper.printCache(zkMap);
return false;
}
// everything in cache is also in map
for (String path : cache.keySet()) {
ZNode cacheNode = cache.get(path);
ZNode zkNode = zkMap.get(path);
if (zkNode == null) {
// in cache but not on zk
System.err.println("path: " + path + " in cache but not on zk: inCacheNode: " + cacheNode);
return false;
}
if ((zkNode.getData() == null && cacheNode.getData() != null) || (zkNode.getData() != null
&& cacheNode.getData() == null) || (zkNode.getData() != null
&& cacheNode.getData() != null && !zkNode.getData().equals(cacheNode.getData()))) {
// data not equal
System.err.println(
"data mismatch on path: " + path + ", inCache: " + cacheNode.getData() + ", onZk: "
+ zkNode.getData());
return false;
}
if ((zkNode.getChildSet() == null && cacheNode.getChildSet() != null) || (
zkNode.getChildSet() != null && cacheNode.getChildSet() == null) || (
zkNode.getChildSet() != null && cacheNode.getChildSet() != null && !zkNode.getChildSet()
.equals(cacheNode.getChildSet()))) {
// childSet not equal
System.err.println(
"childSet mismatch on path: " + path + ", inCache: " + cacheNode.getChildSet()
+ ", onZk: " + zkNode.getChildSet());
return false;
}
if (needVerifyStat && pathsExcludeForStat != null && !pathsExcludeForStat.contains(path)) {
if (cacheNode.getStat() == null || !zkNode.getStat().equals(cacheNode.getStat())) {
// stat not equal
System.err.println(
"Stat mismatch on path: " + path + ", inCache: " + cacheNode.getStat() + ", onZk: "
+ zkNode.getStat());
return false;
}
}
}
return true;
}
public static StateModelDefinition generateStateModelDefForBootstrap() {
ZNRecord record = new ZNRecord("Bootstrap");
record.setSimpleField(StateModelDefinitionProperty.INITIAL_STATE.toString(), "IDLE");
List<String> statePriorityList = new ArrayList<String>();
statePriorityList.add("ONLINE");
statePriorityList.add("BOOTSTRAP");
statePriorityList.add("OFFLINE");
statePriorityList.add("IDLE");
statePriorityList.add("DROPPED");
statePriorityList.add("ERROR");
record.setListField(StateModelDefinitionProperty.STATE_PRIORITY_LIST.toString(),
statePriorityList);
for (String state : statePriorityList) {
String key = state + ".meta";
Map<String, String> metadata = new HashMap<String, String>();
if (state.equals("ONLINE")) {
metadata.put("count", "R");
record.setMapField(key, metadata);
} else if (state.equals("BOOTSTRAP")) {
metadata.put("count", "-1");
record.setMapField(key, metadata);
} else if (state.equals("OFFLINE")) {
metadata.put("count", "-1");
record.setMapField(key, metadata);
} else if (state.equals("IDLE")) {
metadata.put("count", "-1");
record.setMapField(key, metadata);
} else if (state.equals("DROPPED")) {
metadata.put("count", "-1");
record.setMapField(key, metadata);
} else if (state.equals("ERROR")) {
metadata.put("count", "-1");
record.setMapField(key, metadata);
}
}
for (String state : statePriorityList) {
String key = state + ".next";
if (state.equals("ONLINE")) {
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("BOOTSTRAP", "OFFLINE");
metadata.put("OFFLINE", "OFFLINE");
metadata.put("DROPPED", "OFFLINE");
metadata.put("IDLE", "OFFLINE");
record.setMapField(key, metadata);
} else if (state.equals("BOOTSTRAP")) {
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("ONLINE", "ONLINE");
metadata.put("OFFLINE", "OFFLINE");
metadata.put("DROPPED", "OFFLINE");
metadata.put("IDLE", "OFFLINE");
record.setMapField(key, metadata);
} else if (state.equals("OFFLINE")) {
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("ONLINE", "BOOTSTRAP");
metadata.put("BOOTSTRAP", "BOOTSTRAP");
metadata.put("DROPPED", "IDLE");
metadata.put("IDLE", "IDLE");
record.setMapField(key, metadata);
} else if (state.equals("IDLE")) {
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("ONLINE", "OFFLINE");
metadata.put("BOOTSTRAP", "OFFLINE");
metadata.put("OFFLINE", "OFFLINE");
metadata.put("DROPPED", "DROPPED");
record.setMapField(key, metadata);
} else if (state.equals("ERROR")) {
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("IDLE", "IDLE");
record.setMapField(key, metadata);
}
}
List<String> stateTransitionPriorityList = new ArrayList<String>();
stateTransitionPriorityList.add("ONLINE-OFFLINE");
stateTransitionPriorityList.add("BOOTSTRAP-ONLINE");
stateTransitionPriorityList.add("OFFLINE-BOOTSTRAP");
stateTransitionPriorityList.add("BOOTSTRAP-OFFLINE");
stateTransitionPriorityList.add("OFFLINE-IDLE");
stateTransitionPriorityList.add("IDLE-OFFLINE");
stateTransitionPriorityList.add("IDLE-DROPPED");
stateTransitionPriorityList.add("ERROR-IDLE");
record.setListField(StateModelDefinitionProperty.STATE_TRANSITION_PRIORITYLIST.toString(),
stateTransitionPriorityList);
return new StateModelDefinition(record);
}
public static String znrecordToString(ZNRecord record) {
StringBuffer sb = new StringBuffer();
sb.append(record.getId() + "\n");
Map<String, String> simpleFields = record.getSimpleFields();
if (simpleFields != null) {
sb.append("simpleFields\n");
for (String key : simpleFields.keySet()) {
sb.append(" " + key + "\t: " + simpleFields.get(key) + "\n");
}
}
Map<String, List<String>> listFields = record.getListFields();
sb.append("listFields\n");
for (String key : listFields.keySet()) {
List<String> list = listFields.get(key);
sb.append(" " + key + "\t: ");
for (String listValue : list) {
sb.append(listValue + ", ");
}
sb.append("\n");
}
Map<String, Map<String, String>> mapFields = record.getMapFields();
sb.append("mapFields\n");
for (String key : mapFields.keySet()) {
Map<String, String> map = mapFields.get(key);
sb.append(" " + key + "\t: \n");
for (String mapKey : map.keySet()) {
sb.append(" " + mapKey + "\t: " + map.get(mapKey) + "\n");
}
}
return sb.toString();
}
public interface Verifier {
boolean verify() throws Exception;
}
public static boolean verify(Verifier verifier, long timeout) throws Exception {
long start = System.currentTimeMillis();
do {
boolean result = verifier.verify();
boolean isTimedout = (System.currentTimeMillis() - start) > timeout;
if (result || isTimedout) {
if (isTimedout && !result) {
LOG.error("verifier time out, consider try longer timeout, stack trace{}",
Arrays.asList(Thread.currentThread().getStackTrace()));
}
return result;
}
Thread.sleep(50);
} while (true);
}
// debug code
public static String printHandlers(ZkTestManager manager) {
StringBuilder sb = new StringBuilder();
List<CallbackHandler> handlers = manager.getHandlers();
sb.append(manager.getInstanceName() + " has " + handlers.size() + " cb-handlers. [");
for (int i = 0; i < handlers.size(); i++) {
CallbackHandler handler = handlers.get(i);
String path = handler.getPath();
sb.append(
path.substring(manager.getClusterName().length() + 1) + ": " + handler.getListener());
if (i < (handlers.size() - 1)) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
public static void printZkListeners(HelixZkClient client) throws Exception {
Map<String, Set<IZkDataListener>> datalisteners = ZkTestHelper.getZkDataListener(client);
Map<String, Set<IZkChildListener>> childListeners = ZkTestHelper.getZkChildListener(client);
System.out.println("dataListeners {");
for (String path : datalisteners.keySet()) {
System.out.println("\t" + path + ": ");
Set<IZkDataListener> set = datalisteners.get(path);
for (IZkDataListener listener : set) {
CallbackHandler handler = (CallbackHandler) listener;
System.out.println("\t\t" + handler.getListener());
}
}
System.out.println("}");
System.out.println("childListeners {");
for (String path : childListeners.keySet()) {
System.out.println("\t" + path + ": ");
Set<IZkChildListener> set = childListeners.get(path);
for (IZkChildListener listener : set) {
CallbackHandler handler = (CallbackHandler) listener;
System.out.println("\t\t" + handler.getListener());
}
}
System.out.println("}");
}
}
| 9,403 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/ThreadLeakageChecker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.helix;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.helix.common.ZkTestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThreadLeakageChecker {
private final static Logger LOG = LoggerFactory.getLogger(ThreadLeakageChecker.class);
private static ThreadGroup getRootThreadGroup() {
ThreadGroup candidate = Thread.currentThread().getThreadGroup();
while (candidate.getParent() != null) {
candidate = candidate.getParent();
}
return candidate;
}
private static List<Thread> getAllThreads() {
ThreadGroup rootThreadGroup = getRootThreadGroup();
Thread[] threads = new Thread[32];
int count = rootThreadGroup.enumerate(threads);
while (count == threads.length) {
threads = new Thread[threads.length * 2];
count = rootThreadGroup.enumerate(threads);
}
return Arrays.asList(Arrays.copyOf(threads, count));
}
private static final String[] ZKSERVER_THRD_PATTERN =
{"SessionTracker", "NIOServerCxn", "SyncThread:", "ProcessThread"};
private static final String[] ZKSESSION_THRD_PATTERN =
new String[]{"ZkClient-EventThread", "ZkClient-AsyncCallback", "-EventThread", "-SendThread"};
private static final String[] FORKJOIN_THRD_PATTERN = new String[]{"ForkJoinPool"};
private static final String[] TIMER_THRD_PATTERN = new String[]{"time"};
private static final String[] TASKSTATEMODEL_THRD_PATTERN = new String[]{"TaskStateModel"};
/*
* The two threshold -- warning and limit, are mostly empirical.
*
* ZkServer, current version has only 4 threads. In case later version use more, we the limit to 100.
* The reasoning is that these ZkServer threads are not deemed as leaking no matter how much they have.
*
* ZkSession is the ZkClient and native Zookeeper client we have. ZkTestBase has 12 at starting up time.
* Thus, if there is more than that, it is the test code leaking ZkClient.
*
* ForkJoin is created by using parallel stream or similar Java features. This is out of our control.
* Similar to ZkServer. The limit is to 100 while keep a small _warningLimit.
*
* Timer should not happen. Setting limit to 2 not 0 mostly because even when you cancel the timer
* thread, it may take some not deterministic time for it to go away. So give it some slack here
*
* Also note, this ThreadLeakage checker depends on the fact that tests are running sequentially.
* Otherwise, the report is not going to be accurate.
*/
private static enum ThreadCategory {
ZkServer("zookeeper server threads", 4, 100, ZKSERVER_THRD_PATTERN),
ZkSession("zkclient/zooKeeper session threads", 12, 12, ZKSESSION_THRD_PATTERN),
ForkJoin("fork join pool threads", 2, 100, FORKJOIN_THRD_PATTERN),
Timer("timer threads", 0, 2, TIMER_THRD_PATTERN),
TaskStateModel("TaskStateModel threads", 0, 0, TASKSTATEMODEL_THRD_PATTERN),
Other("Other threads", 0, 2, new String[]{""});
private String _description;
private List<String> _pattern;
private int _warningLimit;
private int _limit;
public String getDescription() {
return _description;
}
public Predicate<String> getMatchPred() {
if (this.name() != ThreadCategory.Other.name()) {
Predicate<String> pred = target -> {
for (String p : _pattern) {
if (target.toLowerCase().contains(p.toLowerCase())) {
return true;
}
}
return false;
};
return pred;
}
List<Predicate<String>> predicateList = new ArrayList<>();
for (ThreadCategory threadCategory : ThreadCategory.values()) {
if (threadCategory == ThreadCategory.Other) {
continue;
}
predicateList.add(threadCategory.getMatchPred());
}
Predicate<String> pred = target -> {
for (Predicate<String> p : predicateList) {
if (p.test(target)) {
return false;
}
}
return true;
};
return pred;
}
public int getWarningLimit() {
return _warningLimit;
}
public int getLimit() {
return _limit;
}
private ThreadCategory(String description, int warningLimit, int limit, String[] patterns) {
_description = description;
_pattern = Arrays.asList(patterns);
_warningLimit = warningLimit;
_limit = limit;
}
}
public static boolean afterClassCheck(String classname) {
ZkTestBase.reportPhysicalMemory();
// step 1: get all active threads
List<Thread> threads = getAllThreads();
LOG.info(classname + " has active threads cnt:" + threads.size());
// step 2: categorize threads
Map<String, List<Thread>> threadByName = null;
Map<ThreadCategory, Integer> threadByCnt = new HashMap<>();
Map<ThreadCategory, Set<Thread>> threadByCat = new HashMap<>();
try {
threadByName = threads.
stream().
filter(p -> p.getThreadGroup() != null && p.getThreadGroup().getName() != null
&& ! "system".equals(p.getThreadGroup().getName())).
collect(Collectors.groupingBy(p -> p.getName()));
} catch (Exception e) {
LOG.error("Filtering thread failure with exception:", e);
}
threadByName.entrySet().stream().forEach(entry -> {
String key = entry.getKey(); // thread name
Arrays.asList(ThreadCategory.values()).stream().forEach(category -> {
if (category.getMatchPred().test(key)) {
Integer count = threadByCnt.containsKey(category) ? threadByCnt.get(category) : 0;
threadByCnt.put(category, count + entry.getValue().size());
Set<Thread> thisSet = threadByCat.getOrDefault(category, new HashSet<>());
thisSet.addAll(entry.getValue());
threadByCat.put(category, thisSet);
}
});
});
// todo: We should make the following System.out as LOG.INfO once we achieve 0 thread leakage.
// todo: also the calling point of this method would fail the test
// step 3: enforce checking policy
boolean checkStatus = true;
for (ThreadCategory threadCategory : ThreadCategory.values()) {
int limit = threadCategory.getLimit();
int warningLimit = threadCategory.getWarningLimit();
Integer categoryThreadCnt = threadByCnt.get(threadCategory);
if (categoryThreadCnt != null) {
boolean dumpThread = false;
if (categoryThreadCnt > limit) {
checkStatus = false;
LOG.info(
"Failure " + threadCategory.getDescription() + " has " + categoryThreadCnt + " thread");
dumpThread = true;
} else if (categoryThreadCnt > warningLimit) {
LOG.info(
"Warning " + threadCategory.getDescription() + " has " + categoryThreadCnt + " thread");
dumpThread = true;
} else {
LOG.info(threadCategory.getDescription() + " has " + categoryThreadCnt + " thread");
}
if (!dumpThread) {
continue;
}
// print first 100 thread names
int i = 0;
for (Thread t : threadByCat.get(threadCategory)) {
LOG.debug(i + " thread:" + t.getName());
i++;
if (i == 100) {
LOG.debug(" skipping the rest");
break;
}
}
}
}
return checkStatus;
}
}
| 9,404 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestZkBasis.java
|
package org.apache.helix;
/*
* 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.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.zkclient.IZkChildListener;
import org.apache.helix.zookeeper.zkclient.IZkDataListener;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* test zookeeper basis
*/
public class TestZkBasis extends ZkUnitTestBase {
class ZkListener implements IZkDataListener, IZkChildListener {
String _parentPath = null;
String _dataDeletePath = null;
List<String> _currentChilds = Collections.emptyList(); // make sure it's set to null in
// #handleChildChange()
CountDownLatch _childChangeCountDown = new CountDownLatch(1);
CountDownLatch _dataDeleteCountDown = new CountDownLatch(1);
@Override
public void handleChildChange(String parentPath, List<String> currentChilds) {
_parentPath = parentPath;
_currentChilds = currentChilds;
_childChangeCountDown.countDown();
}
@Override
public void handleDataChange(String dataPath, Object data) {
// To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void handleDataDeleted(String dataPath) {
_dataDeletePath = dataPath;
_dataDeleteCountDown.countDown();
}
}
@Test
public void testZkSessionExpiry() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
String path = String.format("/%s", clusterName);
client.createEphemeral(path);
String oldSessionId = ZkTestHelper.getSessionId(client);
ZkTestHelper.expireSession(client);
String newSessionId = ZkTestHelper.getSessionId(client);
Assert.assertNotSame(newSessionId, oldSessionId);
Assert.assertFalse(client.exists(path), "Ephemeral znode should be gone after session expiry");
client.close();
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testCloseZkClient() {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
String path = String.format("/%s", clusterName);
client.createEphemeral(path);
client.close();
Assert.assertFalse(_gZkClient.exists(path),
"Ephemeral node: " + path + " should be removed after ZkClient#close()");
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testCloseZkClientInZkClientEventThread() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
final CountDownLatch waitCallback = new CountDownLatch(1);
final ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
String path = String.format("/%s", clusterName);
client.createEphemeral(path);
client.subscribeDataChanges(path, new IZkDataListener() {
@Override
public void handleDataDeleted(String dataPath) {
}
@Override
public void handleDataChange(String dataPath, Object data) {
client.close();
waitCallback.countDown();
}
});
client.writeData(path, new ZNRecord("test"));
waitCallback.await();
Assert.assertFalse(_gZkClient.exists(path), "Ephemeral node: " + path
+ " should be removed after ZkClient#close() in its own event-thread");
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
/**
* test zk watchers are renewed automatically after session expiry
* zookeeper-client side keeps all registered watchers see ZooKeeper.WatchRegistration.register()
* after session expiry, all watchers are renewed
* if a path that has watches on it has been removed during session expiry,
* the watchers on that path will still get callbacks after session renewal, especially:
* a data-watch will get data-deleted callback
* a child-watch will get a child-change callback with current-child-list = null
* this can be used for cleanup watchers on the zookeeper-client side
*/
@Test
public void testWatchRenew() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String testName = className + "_" + methodName;
final ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
// make sure "/testName/test" doesn't exist
final String path = "/" + testName + "/test";
client.delete(path);
ZkListener listener = new ZkListener();
client.subscribeDataChanges(path, listener);
client.subscribeChildChanges(path, listener);
ZkTestHelper.expireSession(client);
boolean succeed = listener._childChangeCountDown.await(10, TimeUnit.SECONDS);
Assert.assertTrue(succeed,
"fail to wait on child-change count-down in 10 seconds after session-expiry");
Assert.assertEquals(listener._parentPath, path,
"fail to get child-change callback after session-expiry");
Assert.assertNull(listener._currentChilds,
"fail to get child-change callback with currentChilds=null after session expiry");
succeed = listener._dataDeleteCountDown.await(10, TimeUnit.SECONDS);
Assert.assertTrue(succeed,
"fail to wait on data-delete count-down in 10 seconds after session-expiry");
Assert.assertEquals(listener._dataDeletePath, path,
"fail to get data-delete callback after session-expiry");
client.close();
}
/**
* after calling zkclient#unsubscribeXXXListener()
* an already registered watch will not be removed from ZooKeeper#watchManager#XXXWatches
* immediately.
* the watch will get removed on the following conditions:
* 1) there is a set/delete on the listening path via the zkclient
* 2) session expiry on the zkclient (i.e. the watch will not be renewed after session expiry)
* @throws Exception
*/
@Test
public void testWatchRemove() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String testName = className + "_" + methodName;
final ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
// make sure "/testName/test" doesn't exist
final String path = "/" + testName + "/test";
client.createPersistent(path, true);
ZkListener listener = new ZkListener();
client.subscribeDataChanges(path, listener);
client.subscribeChildChanges(path, listener);
// listener should be in both ZkClient#_dataListener and ZkClient#_childListener set
Map<String, Set<IZkDataListener>> dataListenerMap = ZkTestHelper.getZkDataListener(client);
Assert.assertEquals(dataListenerMap.size(), 1, "ZkClient#_dataListener should have 1 listener");
Set<IZkDataListener> dataListenerSet = dataListenerMap.get(path);
Assert.assertNotNull(dataListenerSet,
"ZkClient#_dataListener should have 1 listener on path: " + path);
Assert.assertEquals(dataListenerSet.size(), 1,
"ZkClient#_dataListener should have 1 listener on path: " + path);
Map<String, Set<IZkChildListener>> childListenerMap = ZkTestHelper.getZkChildListener(client);
Assert.assertEquals(childListenerMap.size(), 1,
"ZkClient#_childListener should have 1 listener");
Set<IZkChildListener> childListenerSet = childListenerMap.get(path);
Assert.assertNotNull(childListenerSet,
"ZkClient#_childListener should have 1 listener on path: " + path);
Assert.assertEquals(childListenerSet.size(), 1,
"ZkClient#_childListener should have 1 listener on path: " + path);
// watch should be in ZooKeeper#watchManager#XXXWatches
Map<String, List<String>> watchMap = ZkTestHelper.getZkWatch(client);
// System.out.println("watchMap1: " + watchMap);
List<String> dataWatch = watchMap.get("dataWatches");
Assert.assertNotNull(dataWatch,
"ZooKeeper#watchManager#dataWatches should have 1 data watch on path: " + path);
Assert.assertEquals(dataWatch.size(), 1,
"ZooKeeper#watchManager#dataWatches should have 1 data watch on path: " + path);
Assert.assertEquals(dataWatch.get(0), path,
"ZooKeeper#watchManager#dataWatches should have 1 data watch on path: " + path);
List<String> childWatch = watchMap.get("childWatches");
Assert.assertNotNull(childWatch,
"ZooKeeper#watchManager#childWatches should have 1 child watch on path: " + path);
Assert.assertEquals(childWatch.size(), 1,
"ZooKeeper#watchManager#childWatches should have 1 child watch on path: " + path);
Assert.assertEquals(childWatch.get(0), path,
"ZooKeeper#watchManager#childWatches should have 1 child watch on path: " + path);
client.unsubscribeDataChanges(path, listener);
client.unsubscribeChildChanges(path, listener);
// System.out.println("watchMap2: " + watchMap);
ZkTestHelper.expireSession(client);
// after session expiry, those watches should be removed
watchMap = ZkTestHelper.getZkWatch(client);
// System.out.println("watchMap3: " + watchMap);
dataWatch = watchMap.get("dataWatches");
Assert.assertTrue(dataWatch.isEmpty(), "ZooKeeper#watchManager#dataWatches should be empty");
childWatch = watchMap.get("childWatches");
Assert.assertTrue(childWatch.isEmpty(), "ZooKeeper#watchManager#childWatches should be empty");
client.close();
deleteCluster(testName);
}
}
| 9,405 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/DummyProcessThread.java
|
package org.apache.helix;
/*
* 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.mock.participant.DummyProcess.DummyLeaderStandbyStateModelFactory;
import org.apache.helix.mock.participant.DummyProcess.DummyMasterSlaveStateModelFactory;
import org.apache.helix.mock.participant.DummyProcess.DummyOnlineOfflineStateModelFactory;
import org.apache.helix.participant.StateMachineEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DummyProcessThread implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(DummyProcessThread.class);
private final HelixManager _manager;
private final String _instanceName;
public DummyProcessThread(HelixManager manager, String instanceName) {
_manager = manager;
_instanceName = instanceName;
}
@Override
public void run() {
try {
DummyMasterSlaveStateModelFactory stateModelFactory = new DummyMasterSlaveStateModelFactory(0);
StateMachineEngine stateMach = _manager.getStateMachineEngine();
stateMach.registerStateModelFactory("MasterSlave", stateModelFactory);
DummyLeaderStandbyStateModelFactory stateModelFactory1 =
new DummyLeaderStandbyStateModelFactory(10);
DummyOnlineOfflineStateModelFactory stateModelFactory2 =
new DummyOnlineOfflineStateModelFactory(10);
stateMach.registerStateModelFactory("LeaderStandby", stateModelFactory1);
stateMach.registerStateModelFactory("OnlineOffline", stateModelFactory2);
_manager.connect();
Thread.currentThread().join();
} catch (InterruptedException e) {
String msg =
"participant:" + _instanceName + ", " + Thread.currentThread().getName() + " interrupted";
LOG.info(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 9,406 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestHelixTaskExecutor.java
|
package org.apache.helix;
/*
* 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.PropertyKey.Builder;
import org.apache.helix.messaging.handling.AsyncCallbackService;
import org.apache.helix.messaging.handling.HelixStateTransitionHandler;
import org.apache.helix.messaging.handling.HelixTask;
import org.apache.helix.mock.MockManager;
import org.apache.helix.mock.participant.MockHelixTaskExecutor;
import org.apache.helix.mock.statemodel.MockMasterSlaveStateModel;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.tools.StateModelConfigGenerator;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class TestHelixTaskExecutor {
@Test()
public void testCMTaskExecutor() throws Exception {
System.out.println("START TestCMTaskExecutor");
String msgId = "TestMessageId";
Message message = new Message(MessageType.TASK_REPLY, msgId);
message.setMsgId(msgId);
message.setSrcName("cm-instance-0");
message.setTgtName("cm-instance-1");
message.setTgtSessionId("1234");
message.setFromState("Offline");
message.setToState("Slave");
message.setPartitionName("TestDB_0");
message.setResourceName("TestDB");
message.setStateModelDef("MasterSlave");
MockManager manager = new MockManager("clusterName");
HelixDataAccessor accessor = manager.getHelixDataAccessor();
StateModelDefinition stateModelDef =
new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave());
Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.stateModelDef("MasterSlave"), stateModelDef);
MockHelixTaskExecutor executor = new MockHelixTaskExecutor();
MockMasterSlaveStateModel stateModel = new MockMasterSlaveStateModel();
executor.registerMessageHandlerFactory(MessageType.TASK_REPLY.name(),
new AsyncCallbackService());
NotificationContext context = new NotificationContext(manager);
CurrentState currentStateDelta = new CurrentState("TestDB");
currentStateDelta.setState("TestDB_0", "OFFLINE");
StateModelFactory<MockMasterSlaveStateModel> stateModelFactory = new StateModelFactory<MockMasterSlaveStateModel>() {
@Override
public MockMasterSlaveStateModel createNewStateModel(String resource, String partitionName) {
// TODO Auto-generated method stub
return new MockMasterSlaveStateModel();
}
};
HelixStateTransitionHandler handler =
new HelixStateTransitionHandler(stateModelFactory, stateModel, message, context,
currentStateDelta);
HelixTask task = new HelixTask(message, context, handler, executor);
executor.scheduleTask(task);
for (int i = 0; i < 10; i++) {
if (!executor.isDone(task.getTaskId())) {
Thread.sleep(500);
}
}
AssertJUnit.assertTrue(stateModel.stateModelInvoked);
System.out.println("END TestCMTaskExecutor");
}
}
| 9,407 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestPropertyPathBuilder.java
|
package org.apache.helix;
/*
* 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.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class TestPropertyPathBuilder {
@Test
public void testGetPath() {
String actual;
actual = PropertyPathBuilder.idealState("test_cluster");
AssertJUnit.assertEquals(actual, "/test_cluster/IDEALSTATES");
actual = PropertyPathBuilder.idealState("test_cluster", "resource");
AssertJUnit.assertEquals(actual, "/test_cluster/IDEALSTATES/resource");
actual = PropertyPathBuilder.instance("test_cluster", "instanceName1");
AssertJUnit.assertEquals(actual, "/test_cluster/INSTANCES/instanceName1");
actual = PropertyPathBuilder.instanceCurrentState("test_cluster", "instanceName1");
AssertJUnit.assertEquals(actual, "/test_cluster/INSTANCES/instanceName1/CURRENTSTATES");
actual = PropertyPathBuilder.instanceCurrentState("test_cluster", "instanceName1", "sessionId");
AssertJUnit.assertEquals(actual, "/test_cluster/INSTANCES/instanceName1/CURRENTSTATES/sessionId");
actual = PropertyPathBuilder.instanceTaskCurrentState("test_cluster", "instanceName1");
AssertJUnit.assertEquals(actual, "/test_cluster/INSTANCES/instanceName1/TASKCURRENTSTATES");
actual =
PropertyPathBuilder.instanceTaskCurrentState("test_cluster", "instanceName1", "sessionId");
AssertJUnit
.assertEquals(actual, "/test_cluster/INSTANCES/instanceName1/TASKCURRENTSTATES/sessionId");
actual = PropertyPathBuilder.instanceCustomizedState("test_cluster", "instanceName1");
AssertJUnit.assertEquals(actual, "/test_cluster/INSTANCES/instanceName1/CUSTOMIZEDSTATES");
actual = PropertyPathBuilder.instanceCustomizedState("test_cluster", "instanceName1", "customizedState1");
AssertJUnit.assertEquals(actual, "/test_cluster/INSTANCES/instanceName1/CUSTOMIZEDSTATES/customizedState1");
actual = PropertyPathBuilder.controller("test_cluster");
AssertJUnit.assertEquals(actual, "/test_cluster/CONTROLLER");
actual = PropertyPathBuilder.controllerMessage("test_cluster");
AssertJUnit.assertEquals(actual, "/test_cluster/CONTROLLER/MESSAGES");
actual = PropertyPathBuilder.clusterStatus("test_cluster");
Assert.assertEquals(actual, "/test_cluster/STATUS/CLUSTER/test_cluster");
}
}
| 9,408 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestGroupCommit.java
|
package org.apache.helix;
/*
* 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.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.helix.mock.MockBaseDataAccessor;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
public class TestGroupCommit {
// @Test
public void testGroupCommit() throws InterruptedException {
final BaseDataAccessor<ZNRecord> accessor = new MockBaseDataAccessor();
final GroupCommit commit = new GroupCommit();
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(400);
for (int i = 0; i < 2400; i++) {
Runnable runnable = new MyClass(accessor, commit, i);
newFixedThreadPool.submit(runnable);
}
Thread.sleep(10000);
System.out.println(accessor.get("test", null, 0));
System.out.println(accessor.get("test", null, 0).getSimpleFields().size());
}
}
class MyClass implements Runnable {
private final BaseDataAccessor<ZNRecord> store;
private final GroupCommit commit;
private final int i;
public MyClass(BaseDataAccessor<ZNRecord> store, GroupCommit commit, int i) {
this.store = store;
this.commit = commit;
this.i = i;
}
@Override
public void run() {
// System.out.println("START " + System.currentTimeMillis() + " --"
// + Thread.currentThread().getId());
ZNRecord znRecord = new ZNRecord("test");
znRecord.setSimpleField("test_id" + i, "" + i);
commit.commit(store, 0, "test", znRecord);
store.get("test", null, 0).getSimpleField("");
// System.out.println("END " + System.currentTimeMillis() + " --"
// + Thread.currentThread().getId());
}
}
| 9,409 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestHierarchicalDataStore.java
|
package org.apache.helix;
/*
* 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.FileFilter;
import org.apache.helix.controller.HierarchicalDataHolder;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class TestHierarchicalDataStore extends ZkUnitTestBase {
protected static HelixZkClient _zkClient = null;
@Test(groups = { "unitTest"
})
public void testHierarchicalDataStore() {
_zkClient = SharedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(ZK_ADDR));
String path = "/tmp/testHierarchicalDataStore";
FileFilter filter = null;
_zkClient.deleteRecursively(path);
HierarchicalDataHolder<ZNRecord> dataHolder =
new HierarchicalDataHolder<ZNRecord>(_zkClient, path, filter);
dataHolder.print();
AssertJUnit.assertFalse(dataHolder.refreshData());
// write data
add(path, "root data");
AssertJUnit.assertTrue(dataHolder.refreshData());
dataHolder.print();
// add some children
add(path + "/child1", "child 1 data");
add(path + "/child2", "child 2 data");
AssertJUnit.assertTrue(dataHolder.refreshData());
dataHolder.print();
// add some grandchildren
add(path + "/child1" + "/grandchild1", "grand child 1 data");
add(path + "/child1" + "/grandchild2", "grand child 2 data");
AssertJUnit.assertTrue(dataHolder.refreshData());
dataHolder.print();
AssertJUnit.assertFalse(dataHolder.refreshData());
set(path + "/child1", "new child 1 data");
AssertJUnit.assertTrue(dataHolder.refreshData());
dataHolder.print();
deleteCluster("tmp");
}
private void set(String path, String data) {
_zkClient.writeData(path, data);
}
private void add(String path, String data) {
_zkClient.createPersistent(path, true);
_zkClient.writeData(path, data);
}
}
| 9,410 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/ScriptTestHelper.java
|
package org.apache.helix;
/*
* 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.File;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
public class ScriptTestHelper {
private static final Logger LOG = LoggerFactory.getLogger(ScriptTestHelper.class);
public static final String INTEGRATION_SCRIPT_DIR = "src/main/scripts/integration-test/script";
public static final String INTEGRATION_TEST_DIR = "src/main/scripts/integration-test/testcases";
public static final String INTEGRATION_LOG_DIR = "src/main/scripts/integration-test/var/log";
public static final long EXEC_TIMEOUT = 1200;
public static String getPrefix() {
StringBuilder prefixBuilder = new StringBuilder("");
String prefix = "";
String filepath = INTEGRATION_SCRIPT_DIR;
File integrationScriptDir = new File(filepath);
while (!integrationScriptDir.exists()) {
prefixBuilder.append("../");
prefix = prefixBuilder.toString();
integrationScriptDir = new File(prefix + filepath);
// Give up
if (prefix.length() > 30) {
return "";
}
}
return new File(prefix).getAbsolutePath() + "/";
}
public static ExternalCommand runCommandLineTest(String testName, String... arguments)
throws IOException, InterruptedException, TimeoutException {
ExternalCommand cmd =
ExternalCommand.executeWithTimeout(new File(getPrefix() + INTEGRATION_TEST_DIR), testName,
EXEC_TIMEOUT, arguments);
int exitValue = cmd.exitValue();
String output = cmd.getStringOutput("UTF8");
if (0 == exitValue) {
LOG.info("Test " + testName + " has run. ExitCode=" + exitValue + ". Command output: "
+ output);
} else {
LOG.warn("Test " + testName + " is FAILING. ExitCode=" + exitValue + ". Command output: "
+ output);
Assert.fail(output);
// return cmd;
}
return cmd;
}
}
| 9,411 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestZKCallback.java
|
package org.apache.helix;
/*
* 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.List;
import java.util.UUID;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.api.listeners.ConfigChangeListener;
import org.apache.helix.api.listeners.CurrentStateChangeListener;
import org.apache.helix.api.listeners.CustomizedStateConfigChangeListener;
import org.apache.helix.api.listeners.CustomizedStateRootChangeListener;
import org.apache.helix.api.listeners.ExternalViewChangeListener;
import org.apache.helix.api.listeners.IdealStateChangeListener;
import org.apache.helix.api.listeners.LiveInstanceChangeListener;
import org.apache.helix.api.listeners.MessageListener;
import org.apache.helix.api.listeners.TaskCurrentStateChangeListener;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.CustomizedStateConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.apache.helix.tools.ClusterSetup;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestZKCallback extends ZkUnitTestBase {
private final String clusterName = CLUSTER_PREFIX + "_" + getShortClassName();
private static String[] createArgs(String str) {
String[] split = str.split("[ ]+");
System.out.println(Arrays.toString(split));
return split;
}
public class TestCallbackListener implements MessageListener, LiveInstanceChangeListener,
ConfigChangeListener, CurrentStateChangeListener,
TaskCurrentStateChangeListener,
CustomizedStateConfigChangeListener,
CustomizedStateRootChangeListener,
ExternalViewChangeListener,
IdealStateChangeListener {
boolean externalViewChangeReceived = false;
boolean liveInstanceChangeReceived = false;
boolean configChangeReceived = false;
boolean currentStateChangeReceived = false;
boolean taskCurrentStateChangeReceived = false;
boolean customizedStateConfigChangeReceived = false;
boolean customizedStateRootChangeReceived = false;
boolean messageChangeReceived = false;
boolean idealStateChangeReceived = false;
@Override
public void onExternalViewChange(List<ExternalView> externalViewList,
NotificationContext changeContext) {
externalViewChangeReceived = true;
}
@Override
public void onStateChange(String instanceName, List<CurrentState> statesInfo,
NotificationContext changeContext) {
currentStateChangeReceived = true;
}
@Override
public void onTaskCurrentStateChange(String instanceName, List<CurrentState> statesInfo,
NotificationContext changeContext) {
taskCurrentStateChangeReceived = true;
}
@Override
public void onConfigChange(List<InstanceConfig> configs, NotificationContext changeContext) {
configChangeReceived = true;
}
@Override
public void onLiveInstanceChange(List<LiveInstance> liveInstances,
NotificationContext changeContext) {
liveInstanceChangeReceived = true;
}
@Override
public void onMessage(String instanceName, List<Message> messages,
NotificationContext changeContext) {
messageChangeReceived = true;
}
void Reset() {
externalViewChangeReceived = false;
liveInstanceChangeReceived = false;
configChangeReceived = false;
currentStateChangeReceived = false;
customizedStateConfigChangeReceived = false;
customizedStateRootChangeReceived = false;
messageChangeReceived = false;
idealStateChangeReceived = false;
}
@Override
public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) {
// TODO Auto-generated method stub
idealStateChangeReceived = true;
}
@Override
public void onCustomizedStateRootChange(String instanceName, List<String> customizedStateTypes,
NotificationContext changeContext) {
// TODO Auto-generated method stub
customizedStateRootChangeReceived = true;
}
@Override
public void onCustomizedStateConfigChange(CustomizedStateConfig customizedStateConfig,
NotificationContext context) {
// TODO Auto-generated method stub
customizedStateConfigChangeReceived = true;
}
}
@Test()
public void testInvocation() throws Exception {
HelixManager testHelixManager =
HelixManagerFactory.getZKHelixManager(clusterName, "localhost_8900",
InstanceType.PARTICIPANT, ZK_ADDR);
testHelixManager.connect();
try {
TestZKCallback test = new TestZKCallback();
TestZKCallback.TestCallbackListener testListener = test.new TestCallbackListener();
testHelixManager.addMessageListener(testListener, "localhost_8900");
testHelixManager.addCurrentStateChangeListener(testListener, "localhost_8900",
testHelixManager.getSessionId());
testHelixManager.addTaskCurrentStateChangeListener(testListener, "localhost_8900",
testHelixManager.getSessionId());
testHelixManager.addCustomizedStateRootChangeListener(testListener, "localhost_8900");
testHelixManager.addConfigChangeListener(testListener);
testHelixManager.addIdealStateChangeListener(testListener);
testHelixManager.addExternalViewChangeListener(testListener);
testHelixManager.addLiveInstanceChangeListener(testListener);
// Initial add listener should trigger the first execution of the
// listener callbacks
AssertJUnit.assertTrue(
testListener.configChangeReceived & testListener.currentStateChangeReceived & testListener.externalViewChangeReceived
& testListener.idealStateChangeReceived & testListener.liveInstanceChangeReceived & testListener.messageChangeReceived);
testListener.Reset();
HelixDataAccessor accessor = testHelixManager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
ExternalView extView = new ExternalView("db-12345");
accessor.setProperty(keyBuilder.externalView("db-12345"), extView);
boolean result = TestHelper.verify(() -> {
return testListener.externalViewChangeReceived;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
testListener.Reset();
CurrentState curState = new CurrentState("db-12345");
curState.setSessionId("sessionId");
curState.setStateModelDefRef("StateModelDef");
accessor.setProperty(keyBuilder
.currentState("localhost_8900", testHelixManager.getSessionId(), curState.getId()),
curState);
result = TestHelper.verify(() -> {
return testListener.currentStateChangeReceived;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
testListener.Reset();
CurrentState taskCurState = new CurrentState("db-12345");
taskCurState.setSessionId("sessionId");
taskCurState.setStateModelDefRef("StateModelDef");
accessor.setProperty(keyBuilder
.taskCurrentState("localhost_8900", testHelixManager.getSessionId(),
taskCurState.getId()), taskCurState);
result = TestHelper.verify(() -> {
return testListener.taskCurrentStateChangeReceived;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
testListener.Reset();
IdealState idealState = new IdealState("db-1234");
idealState.setNumPartitions(400);
idealState.setReplicas(Integer.toString(2));
idealState.setStateModelDefRef("StateModeldef");
accessor.setProperty(keyBuilder.idealStates("db-1234"), idealState);
result = TestHelper.verify(() -> {
return testListener.idealStateChangeReceived;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
testListener.Reset();
// dummyRecord = new ZNRecord("db-12345");
// dataAccessor.setProperty(PropertyType.IDEALSTATES, idealState, "db-12345"
// );
// Thread.sleep(100);
// AssertJUnit.assertTrue(testListener.idealStateChangeReceived);
// testListener.Reset();
// dummyRecord = new ZNRecord("localhost:8900");
// List<ZNRecord> recList = new ArrayList<ZNRecord>();
// recList.add(dummyRecord);
testListener.Reset();
Message message = new Message(MessageType.STATE_TRANSITION, UUID.randomUUID().toString());
message.setTgtSessionId("*");
message.setResourceName("testResource");
message.setPartitionName("testPartitionKey");
message.setStateModelDef("MasterSlave");
message.setToState("toState");
message.setFromState("fromState");
message.setTgtName("testTarget");
message.setStateModelFactoryName(HelixConstants.DEFAULT_STATE_MODEL_FACTORY);
accessor.setProperty(keyBuilder.message("localhost_8900", message.getId()), message);
result = TestHelper.verify(() -> {
return testListener.messageChangeReceived;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
testListener.Reset();
// dummyRecord = new ZNRecord("localhost_9801");
LiveInstance liveInstance = new LiveInstance("localhost_9801");
liveInstance.setSessionId(UUID.randomUUID().toString());
liveInstance.setHelixVersion(UUID.randomUUID().toString());
accessor.setProperty(keyBuilder.liveInstance("localhost_9801"), liveInstance);
result = TestHelper.verify(() -> {
return testListener.liveInstanceChangeReceived;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
testListener.Reset();
// dataAccessor.setNodeConfigs(recList); Thread.sleep(100);
// AssertJUnit.assertTrue(testListener.configChangeReceived);
// testListener.Reset();
accessor.removeProperty(keyBuilder.liveInstance("localhost_8900"));
accessor.removeProperty(keyBuilder.liveInstance("localhost_9801"));
} finally {
if (testHelixManager.isConnected()) {
testHelixManager.disconnect();
}
}
}
@BeforeClass()
public void beforeClass() throws Exception {
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -addCluster "
+ clusterName));
// ClusterSetup
// .processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR +
// " -addCluster relay-cluster-12345"));
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -addResource "
+ clusterName + " db-12345 120 MasterSlave"));
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -addNode " + clusterName
+ " localhost:8900"));
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -addNode " + clusterName
+ " localhost:8901"));
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -addNode " + clusterName
+ " localhost:8902"));
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -addNode " + clusterName
+ " localhost:8903"));
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -addNode " + clusterName
+ " localhost:8904"));
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " -rebalance "
+ clusterName + " db-12345 3"));
}
@AfterClass()
public void afterClass() {
deleteCluster(clusterName);
}
}
| 9,412 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestListenerCallback.java
|
package org.apache.helix;
/*
* 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.PropertyKey.Builder;
import org.apache.helix.api.listeners.ClusterConfigChangeListener;
import org.apache.helix.api.listeners.InstanceConfigChangeListener;
import org.apache.helix.api.listeners.ResourceConfigChangeListener;
import org.apache.helix.api.listeners.ScopedConfigChangeListener;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.ResourceConfig;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestListenerCallback extends ZkUnitTestBase {
class TestScopedConfigListener implements ScopedConfigChangeListener {
boolean _configChanged = false;
int _configSize = 0;
@Override
public void onConfigChange(List<HelixProperty> configs, NotificationContext context) {
_configChanged = true;
_configSize = configs.size();
}
public void reset() {
_configChanged = false;
_configSize = 0;
}
}
class TestConfigListener implements InstanceConfigChangeListener, ClusterConfigChangeListener,
ResourceConfigChangeListener {
boolean _instanceConfigChanged = false;
boolean _resourceConfigChanged = false;
boolean _clusterConfigChanged = false;
List<ResourceConfig> _resourceConfigs;
List<InstanceConfig> _instanceConfigs;
ClusterConfig _clusterConfig;
@Override
public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs,
NotificationContext context) {
_instanceConfigChanged = true;
_instanceConfigs = instanceConfigs;
}
@Override
public void onClusterConfigChange(ClusterConfig clusterConfig, NotificationContext context) {
_clusterConfigChanged = true;
_clusterConfig = clusterConfig;
}
@Override
public void onResourceConfigChange(List<ResourceConfig> resourceConfigs,
NotificationContext context) {
_resourceConfigChanged = true;
_resourceConfigs = resourceConfigs;
}
public void reset() {
_instanceConfigChanged = false;
_resourceConfigChanged = false;
_clusterConfigChanged = false;
_resourceConfigs = null;
_instanceConfigs = null;
_clusterConfig = null;
}
}
int _numNodes = 3;
int _numResources = 4;
HelixManager _manager;
String _clusterName;
@BeforeClass
public void beforeClass() throws Exception {
_clusterName = TestHelper.getTestClassName();
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
_numResources, // resources
32, // partitions per resource
_numNodes, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
_manager = HelixManagerFactory.getZKHelixManager(_clusterName, "localhost",
InstanceType.SPECTATOR, ZK_ADDR);
_manager.connect();
}
@AfterClass
public void afterClass() throws Exception {
if (_manager != null && _manager.isConnected()) {
_manager.disconnect();
}
TestHelper.dropCluster(_clusterName, _gZkClient);
System.out.println("END " + _clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testConfigChangeListeners() throws Exception {
TestConfigListener listener = new TestConfigListener();
listener.reset();
_manager.addInstanceConfigChangeListener(listener);
boolean result = TestHelper.verify(()-> {
return listener._instanceConfigChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "Should get initial instanceConfig callback invoked");
Assert.assertEquals(listener._instanceConfigs.size(), _numNodes,
"Instance Config size does not match");
listener.reset();
_manager.addClusterfigChangeListener(listener);
result = TestHelper.verify(()-> {
return listener._clusterConfigChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "Should get initial clusterConfig callback invoked");
Assert.assertNotNull(listener._clusterConfig, "Cluster Config size should not be null");
listener.reset();
_manager.addResourceConfigChangeListener(listener);
result = TestHelper.verify(()-> {
return listener._resourceConfigChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "Should get initial resourceConfig callback invoked");
Assert.assertEquals(listener._resourceConfigs.size(), 0, "resource config size does not match");
// test change content
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
String instanceName = "localhost_12918";
HelixProperty value = accessor.getProperty(keyBuilder.instanceConfig(instanceName));
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.instanceConfig(instanceName), value);
result = TestHelper.verify(()-> {
return listener._instanceConfigChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "Should get instanceConfig callback invoked since we change instanceConfig");
Assert.assertEquals(listener._instanceConfigs.size(), _numNodes,
"Instance Config size does not match");
value = accessor.getProperty(keyBuilder.clusterConfig());
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.clusterConfig(), value);
result = TestHelper.verify(()-> {
return listener._clusterConfigChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "Should get clusterConfig callback invoked since we change clusterConfig");
Assert.assertNotNull(listener._clusterConfig, "Cluster Config size should not be null");
String resourceName = "TestDB_0";
value = new HelixProperty(resourceName);
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.resourceConfig(resourceName), value);
result = TestHelper.verify(()-> {
return listener._resourceConfigChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._resourceConfigs.size(), 1, "Resource config size does not match");
listener.reset();
accessor.removeProperty(keyBuilder.resourceConfig(resourceName));
result = TestHelper.verify(()-> {
return listener._resourceConfigChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._resourceConfigs.size(), 0, "Instance Config size does not match");
}
@Test
public void testScopedConfigChangeListener() throws Exception {
TestScopedConfigListener listener = new TestScopedConfigListener();
listener.reset();
_manager.addConfigChangeListener(listener, ConfigScopeProperty.CLUSTER);
boolean result = TestHelper.verify(()-> {
return listener._configChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,"Should get initial clusterConfig callback invoked");
Assert.assertEquals(listener._configSize, 1, "Cluster Config size should be 1");
listener.reset();
_manager.addConfigChangeListener(listener, ConfigScopeProperty.RESOURCE);
result = TestHelper.verify(()-> {
return listener._configChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,
"Should get initial resourceConfig callback invoked");
Assert.assertEquals(listener._configSize, 0, "Resource Config size does not match");
listener.reset();
_manager.addConfigChangeListener(listener, ConfigScopeProperty.PARTICIPANT);
result = TestHelper.verify(()-> {
return listener._configChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,"Should get initial resourceConfig callback invoked");
Assert.assertEquals(listener._configSize, _numNodes, "Instance Config size does not match");
// test change content
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
String instanceName = "localhost_12918";
HelixProperty value = accessor.getProperty(keyBuilder.instanceConfig(instanceName));
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.instanceConfig(instanceName), value);
result = TestHelper.verify(()-> {
return listener._configChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,
"Should get instanceConfig callback invoked since we change instanceConfig");
Assert.assertEquals(listener._configSize, _numNodes, "Instance Config size does not match");
value = accessor.getProperty(keyBuilder.clusterConfig());
value._record.setSimpleField("" + System.currentTimeMillis(), "newClusterValue");
listener.reset();
accessor.setProperty(keyBuilder.clusterConfig(), value);
result = TestHelper.verify(()-> {
return listener._configChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,
"Should get clusterConfig callback invoked since we change clusterConfig");
Assert.assertEquals(listener._configSize, 1, "Cluster Config size does not match");
String resourceName = "TestDB_0";
value = new HelixProperty(resourceName);
value._record.setSimpleField("" + System.currentTimeMillis(), "newValue");
listener.reset();
accessor.setProperty(keyBuilder.resourceConfig(resourceName), value);
result = TestHelper.verify(()-> {
return listener._configChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,
"Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._configSize, 1, "Resource Config size does not match");
listener.reset();
accessor.removeProperty(keyBuilder.resourceConfig(resourceName));
result = TestHelper.verify(()-> {
return listener._configChanged;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,
"Should get resourceConfig callback invoked since we add resourceConfig");
Assert.assertEquals(listener._configSize, 0, "Resource Config size does not match");
}
}
| 9,413 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestEspressoStorageClusterIdealState.java
|
package org.apache.helix;
/*
* 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.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.DefaultIdealStateCalculator;
import org.apache.helix.util.RebalanceUtil;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
public class TestEspressoStorageClusterIdealState {
@Test()
public void testEspressoStorageClusterIdealState() throws Exception {
List<String> instanceNames = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
instanceNames.add("localhost:123" + i);
}
int partitions = 8, replicas = 0;
Map<String, Object> result0 =
DefaultIdealStateCalculator.calculateInitialIdealState(instanceNames, partitions, replicas);
Verify(result0, partitions, replicas);
partitions = 8192;
replicas = 3;
instanceNames.clear();
for (int i = 0; i < 20; i++) {
instanceNames.add("localhost:123" + i);
}
Map<String, Object> resultOriginal =
DefaultIdealStateCalculator.calculateInitialIdealState(instanceNames, partitions, replicas);
Verify(resultOriginal, partitions, replicas);
printStat(resultOriginal);
Map<String, Object> result1 =
DefaultIdealStateCalculator.calculateInitialIdealState(instanceNames, partitions, replicas);
List<String> instanceNames2 = new ArrayList<String>();
for (int i = 30; i < 35; i++) {
instanceNames2.add("localhost:123" + i);
}
DefaultIdealStateCalculator.calculateNextIdealState(instanceNames2, result1);
List<String> instanceNames3 = new ArrayList<String>();
for (int i = 35; i < 40; i++) {
instanceNames3.add("localhost:123" + i);
}
DefaultIdealStateCalculator.calculateNextIdealState(instanceNames3, result1);
Double masterKeepRatio = 0.0, slaveKeepRatio = 0.0;
Verify(result1, partitions, replicas);
double[] result = compareResult(resultOriginal, result1);
masterKeepRatio = result[0];
slaveKeepRatio = result[1];
Assert.assertTrue(0.66 < masterKeepRatio && 0.67 > masterKeepRatio);
Assert.assertTrue(0.49 < slaveKeepRatio && 0.51 > slaveKeepRatio);
}
@Test
public void testRebalance2() {
int partitions = 1256, replicas = 3;
List<String> instanceNames = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
instanceNames.add("localhost:123" + i);
}
Map<String, Object> resultOriginal =
DefaultIdealStateCalculator.calculateInitialIdealState(instanceNames, partitions, replicas);
ZNRecord idealState1 =
DefaultIdealStateCalculator.convertToZNRecord(resultOriginal, "TestDB", "MASTER", "SLAVE");
Map<String, Object> result1 =
RebalanceUtil.buildInternalIdealState(new IdealState(idealState1));
List<String> instanceNames2 = new ArrayList<String>();
for (int i = 30; i < 35; i++) {
instanceNames2.add("localhost:123" + i);
}
Map<String, Object> result2 =
DefaultIdealStateCalculator.calculateNextIdealState(instanceNames2, result1);
Verify(resultOriginal, partitions, replicas);
Verify(result2, partitions, replicas);
Double masterKeepRatio = 0.0, slaveKeepRatio = 0.0;
double[] result = compareResult(resultOriginal, result2);
masterKeepRatio = result[0];
slaveKeepRatio = result[1];
Assert.assertTrue(0.66 < masterKeepRatio && 0.67 > masterKeepRatio);
Assert.assertTrue(0.49 < slaveKeepRatio && 0.51 > slaveKeepRatio);
}
public static void Verify(Map<String, Object> result, int partitions, int replicas) {
Map<String, List<Integer>> masterAssignmentMap =
(Map<String, List<Integer>>) (result.get("MasterAssignmentMap"));
Map<String, Map<String, List<Integer>>> nodeSlaveAssignmentMap =
(Map<String, Map<String, List<Integer>>>) (result.get("SlaveAssignmentMap"));
AssertJUnit.assertTrue(partitions == (Integer) (result.get("partitions")));
// Verify master partitions covers all master partitions on each node
Map<Integer, Integer> masterCounterMap = new TreeMap<Integer, Integer>();
for (int i = 0; i < partitions; i++) {
masterCounterMap.put(i, 0);
}
int minMasters = Integer.MAX_VALUE, maxMasters = Integer.MIN_VALUE;
for (String instanceName : masterAssignmentMap.keySet()) {
List<Integer> masterList = masterAssignmentMap.get(instanceName);
// the assert needs to be changed when weighting is introduced
// AssertJUnit.assertTrue(masterList.size() == partitions /masterAssignmentMap.size() |
// masterList.size() == (partitions /masterAssignmentMap.size()+1) );
for (Integer x : masterList) {
AssertJUnit.assertTrue(masterCounterMap.get(x) == 0);
masterCounterMap.put(x, 1);
}
if (minMasters > masterList.size()) {
minMasters = masterList.size();
}
if (maxMasters < masterList.size()) {
maxMasters = masterList.size();
}
}
// Master partition should be evenly distributed most of the time
System.out.println("Masters: max: " + maxMasters + " Min:" + minMasters);
// Each master partition should occur only once
for (int i = 0; i < partitions; i++) {
AssertJUnit.assertTrue(masterCounterMap.get(i) == 1);
}
AssertJUnit.assertTrue(masterCounterMap.size() == partitions);
// for each node, verify the master partitions and the slave partition assignment map
if (replicas == 0) {
AssertJUnit.assertTrue(nodeSlaveAssignmentMap.size() == 0);
return;
}
AssertJUnit.assertTrue(masterAssignmentMap.size() == nodeSlaveAssignmentMap.size());
for (String instanceName : masterAssignmentMap.keySet()) {
AssertJUnit.assertTrue(nodeSlaveAssignmentMap.containsKey(instanceName));
Map<String, List<Integer>> slaveAssignmentMap = nodeSlaveAssignmentMap.get(instanceName);
Map<Integer, Integer> slaveCountMap = new TreeMap<Integer, Integer>();
List<Integer> masterList = masterAssignmentMap.get(instanceName);
for (Integer masterPartitionId : masterList) {
slaveCountMap.put(masterPartitionId, 0);
}
// Make sure that masterList are covered replica times by the slave assignment.
int minSlaves = Integer.MAX_VALUE, maxSlaves = Integer.MIN_VALUE;
for (String hostInstance : slaveAssignmentMap.keySet()) {
List<Integer> slaveAssignment = slaveAssignmentMap.get(hostInstance);
Set<Integer> occurenceSet = new HashSet<Integer>();
// Each slave should occur only once in the list, since the list is per-node slaves
for (Integer slavePartition : slaveAssignment) {
AssertJUnit.assertTrue(!occurenceSet.contains(slavePartition));
occurenceSet.add(slavePartition);
slaveCountMap.put(slavePartition, slaveCountMap.get(slavePartition) + 1);
}
if (minSlaves > slaveAssignment.size()) {
minSlaves = slaveAssignment.size();
}
if (maxSlaves < slaveAssignment.size()) {
maxSlaves = slaveAssignment.size();
}
}
// check if slave distribution is even
AssertJUnit.assertTrue(maxSlaves - minSlaves <= 1);
// System.out.println("Slaves: max: "+maxSlaves+" Min:"+ minSlaves);
// for each node, the slave assignment map should cover the masters for exactly replica
// times
AssertJUnit.assertTrue(slaveCountMap.size() == masterList.size());
for (Integer masterPartitionId : masterList) {
AssertJUnit.assertTrue(slaveCountMap.get(masterPartitionId) == replicas);
}
}
}
public void printStat(Map<String, Object> result) {
// print out master distribution
// print out slave distribution
}
public static double[] compareResult(Map<String, Object> result1, Map<String, Object> result2) {
double[] result = new double[2];
Map<String, List<Integer>> masterAssignmentMap1 =
(Map<String, List<Integer>>) (result1.get("MasterAssignmentMap"));
Map<String, Map<String, List<Integer>>> nodeSlaveAssignmentMap1 =
(Map<String, Map<String, List<Integer>>>) (result1.get("SlaveAssignmentMap"));
Map<String, List<Integer>> masterAssignmentMap2 =
(Map<String, List<Integer>>) (result2.get("MasterAssignmentMap"));
Map<String, Map<String, List<Integer>>> nodeSlaveAssignmentMap2 =
(Map<String, Map<String, List<Integer>>>) (result2.get("SlaveAssignmentMap"));
int commonMasters = 0;
int commonSlaves = 0;
int partitions = (Integer) (result1.get("partitions"));
int replicas = (Integer) (result1.get("replicas"));
AssertJUnit.assertTrue((Integer) (result2.get("partitions")) == partitions);
AssertJUnit.assertTrue((Integer) (result2.get("replicas")) == replicas);
// masterMap1 maps from partition id to the holder instance name
Map<Integer, String> masterMap1 = new TreeMap<Integer, String>();
for (String instanceName : masterAssignmentMap1.keySet()) {
List<Integer> masterList1 = masterAssignmentMap1.get(instanceName);
for (Integer partition : masterList1) {
AssertJUnit.assertTrue(!masterMap1.containsKey(partition));
masterMap1.put(partition, instanceName);
}
}
// go through masterAssignmentMap2 and find out the common number
for (String instanceName : masterAssignmentMap2.keySet()) {
List<Integer> masterList2 = masterAssignmentMap2.get(instanceName);
for (Integer partition : masterList2) {
if (masterMap1.get(partition).equalsIgnoreCase(instanceName)) {
commonMasters++;
}
}
}
result[0] = 1.0 * commonMasters / partitions;
System.out.println(
commonMasters + " master partitions are kept, " + (partitions - commonMasters)
+ " moved, keep ratio:" + 1.0 * commonMasters / partitions);
// maps from the partition id to the instance names that holds its slave partition
Map<Integer, Set<String>> slaveMap1 = new TreeMap<Integer, Set<String>>();
for (String instanceName : nodeSlaveAssignmentMap1.keySet()) {
Map<String, List<Integer>> slaveAssignment1 = nodeSlaveAssignmentMap1.get(instanceName);
for (String slaveHostName : slaveAssignment1.keySet()) {
List<Integer> slaveList = slaveAssignment1.get(slaveHostName);
for (Integer partition : slaveList) {
if (!slaveMap1.containsKey(partition)) {
slaveMap1.put(partition, new TreeSet<String>());
}
AssertJUnit.assertTrue(!slaveMap1.get(partition).contains(slaveHostName));
slaveMap1.get(partition).add(slaveHostName);
}
}
}
for (String instanceName : nodeSlaveAssignmentMap2.keySet()) {
Map<String, List<Integer>> slaveAssignment2 = nodeSlaveAssignmentMap2.get(instanceName);
for (String slaveHostName : slaveAssignment2.keySet()) {
List<Integer> slaveList = slaveAssignment2.get(slaveHostName);
for (Integer partition : slaveList) {
if (slaveMap1.get(partition).contains(slaveHostName)) {
commonSlaves++;
}
}
}
}
result[1] = 1.0 * commonSlaves / partitions / replicas;
System.out.println(
commonSlaves + " slave partitions are kept, " + (partitions * replicas - commonSlaves)
+ " moved. keep ratio:" + 1.0 * commonSlaves / partitions / replicas);
return result;
}
}
| 9,414 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/ZkTestHelper.java
|
package org.apache.helix;
/*
* 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.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.helix.PropertyKey.Builder;
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.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.zkclient.IZkChildListener;
import org.apache.helix.zookeeper.zkclient.IZkDataListener;
import org.apache.helix.zookeeper.zkclient.IZkStateListener;
import org.apache.helix.zookeeper.zkclient.ZkClient;
import org.apache.helix.zookeeper.zkclient.ZkConnection;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
public class ZkTestHelper {
private static Logger LOG = LoggerFactory.getLogger(ZkTestHelper.class);
private static ExecutorService _executor = Executors.newSingleThreadExecutor();
static {
// Logger.getRootLogger().setLevel(Level.DEBUG);
}
/**
* Simulate a zk state change by calling {@link ZkClient#process(WatchedEvent)} directly
*/
public static void simulateZkStateReconnected(RealmAwareZkClient client) {
ZkClient zkClient = (ZkClient) client;
WatchedEvent event = new WatchedEvent(EventType.None, KeeperState.Disconnected, null);
zkClient.process(event);
event = new WatchedEvent(EventType.None, KeeperState.SyncConnected, null);
zkClient.process(event);
}
/**
* Get zk connection session id
* @param client
* @return
*/
public static String getSessionId(RealmAwareZkClient client) {
ZkConnection connection = (ZkConnection) ((ZkClient) client).getConnection();
ZooKeeper curZookeeper = connection.getZookeeper();
return Long.toHexString(curZookeeper.getSessionId());
}
/**
* Expire current zk session and wait for {@link IZkStateListener#handleNewSession(String)} invoked
* @param client
* @throws Exception
*/
public static void disconnectSession(HelixZkClient client) throws Exception {
final ZkClient zkClient = (ZkClient) client;
IZkStateListener listener = new IZkStateListener() {
@Override
public void handleStateChanged(KeeperState state) throws Exception {
// System.err.println("disconnectSession handleStateChanged. state: " + state);
}
@Override
public void handleNewSession(final String sessionId) throws Exception {
// make sure zkclient is connected again
zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS);
LOG.info("handleNewSession. sessionId: {}.", sessionId);
}
@Override
public void handleSessionEstablishmentError(Throwable var1) throws Exception {
}
};
zkClient.subscribeStateChanges(listener);
ZkConnection connection = (ZkConnection) zkClient.getConnection();
ZooKeeper curZookeeper = connection.getZookeeper();
LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
LOG.info("Process watchEvent: " + event);
}
};
final ZooKeeper dupZookeeper =
new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
// wait until connected, then close
while (dupZookeeper.getState() != States.CONNECTED) {
Thread.sleep(10);
}
dupZookeeper.close();
connection = (ZkConnection) zkClient.getConnection();
curZookeeper = connection.getZookeeper();
zkClient.unsubscribeStateChanges(listener);
// System.err.println("zk: " + oldZookeeper);
LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}
public static void expireSession(RealmAwareZkClient client) throws Exception {
final CountDownLatch waitNewSession = new CountDownLatch(1);
final ZkClient zkClient = (ZkClient) client;
IZkStateListener listener = new IZkStateListener() {
@Override
public void handleStateChanged(KeeperState state) throws Exception {
LOG.info("IZkStateListener#handleStateChanged, state: " + state);
}
@Override
public void handleNewSession(final String sessionId) throws Exception {
// make sure zkclient is connected again
zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS);
LOG.info("handleNewSession. sessionId: {}.", sessionId);
waitNewSession.countDown();
}
@Override
public void handleSessionEstablishmentError(Throwable var1) throws Exception {
}
};
zkClient.subscribeStateChanges(listener);
ZkConnection connection = ((ZkConnection) zkClient.getConnection());
ZooKeeper curZookeeper = connection.getZookeeper();
String oldSessionId = Long.toHexString(curZookeeper.getSessionId());
LOG.info("Before session expiry. sessionId: " + oldSessionId + ", zk: " + curZookeeper);
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
LOG.info("Watcher#process, event: " + event);
}
};
final ZooKeeper dupZookeeper =
new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
// wait until connected, then close
while (dupZookeeper.getState() != States.CONNECTED) {
Thread.sleep(10);
}
Assert.assertEquals(dupZookeeper.getState(), States.CONNECTED,
"Fail to connect to zk using current session info");
dupZookeeper.close();
// make sure session expiry really happens
waitNewSession.await();
zkClient.unsubscribeStateChanges(listener);
connection = (ZkConnection) zkClient.getConnection();
curZookeeper = connection.getZookeeper();
String newSessionId = Long.toHexString(curZookeeper.getSessionId());
LOG.info("After session expiry. sessionId: " + newSessionId + ", zk: " + curZookeeper);
Assert.assertFalse(newSessionId.equals(oldSessionId),
"Fail to expire current session, zk: " + curZookeeper);
}
/**
* expire zk session asynchronously
* @param client
* @throws Exception
*/
public static void asyncExpireSession(RealmAwareZkClient client) throws Exception {
final ZkClient zkClient = (ZkClient) client;
ZkConnection connection = ((ZkConnection) zkClient.getConnection());
ZooKeeper curZookeeper = connection.getZookeeper();
LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
LOG.info("Process watchEvent: " + event);
}
};
final ZooKeeper dupZookeeper =
new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
// wait until connected, then close
while (dupZookeeper.getState() != States.CONNECTED) {
Thread.sleep(10);
}
dupZookeeper.close();
connection = (ZkConnection) zkClient.getConnection();
curZookeeper = connection.getZookeeper();
// System.err.println("zk: " + oldZookeeper);
LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}
/*
* stateMap: partition->instance->state
*/
public static boolean verifyState(RealmAwareZkClient zkclient, String clusterName, String resourceName,
Map<String, Map<String, String>> expectStateMap, String op) {
boolean result = true;
ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(zkclient);
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
Builder keyBuilder = accessor.keyBuilder();
ExternalView extView = accessor.getProperty(keyBuilder.externalView(resourceName));
Map<String, Map<String, String>> actualStateMap = extView.getRecord().getMapFields();
for (String partition : actualStateMap.keySet()) {
for (String expectPartiton : expectStateMap.keySet()) {
if (!partition.matches(expectPartiton)) {
continue;
}
Map<String, String> actualInstanceStateMap = actualStateMap.get(partition);
Map<String, String> expectInstanceStateMap = expectStateMap.get(expectPartiton);
for (String instance : actualInstanceStateMap.keySet()) {
for (String expectInstance : expectStateMap.get(expectPartiton).keySet()) {
if (!instance.matches(expectInstance)) {
continue;
}
String actualState = actualInstanceStateMap.get(instance);
String expectState = expectInstanceStateMap.get(expectInstance);
boolean equals = expectState.equals(actualState);
if (op.equals("==") && !equals || op.equals("!=") && equals) {
System.out.println(
partition + "/" + instance + " state mismatch. actual state: " + actualState
+ ", but expect: " + expectState + ", op: " + op);
result = false;
}
}
}
}
}
return result;
}
/**
* return the number of listeners on given zk-path
* @param zkAddr
* @param path
* @return
* @throws Exception
*/
public static int numberOfListeners(String zkAddr, String path) throws Exception {
Map<String, Set<String>> listenerMap = getListenersByZkPath(zkAddr);
if (listenerMap.containsKey(path)) {
return listenerMap.get(path).size();
}
return 0;
}
/**
* return a map from zk-path to a set of zk-session-id that put watches on the zk-path
* @param zkAddr
* @return
* @throws Exception
*/
public static Map<String, Set<String>> getListenersByZkPath(String zkAddr) throws Exception {
String splits[] = zkAddr.split(":");
Map<String, Set<String>> listenerMap = new TreeMap<String, Set<String>>();
Socket sock = null;
int retry = 5;
while (retry > 0) {
try {
sock = new Socket(splits[0], Integer.parseInt(splits[1]));
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out.println("wchp");
listenerMap.clear();
String lastPath = null;
String line = in.readLine();
while (line != null) {
line = line.trim();
if (line.startsWith("/")) {
lastPath = line;
if (!listenerMap.containsKey(lastPath)) {
listenerMap.put(lastPath, new TreeSet<String>());
}
} else if (line.startsWith("0x")) {
if (lastPath != null && listenerMap.containsKey(lastPath)) {
listenerMap.get(lastPath).add(line);
} else {
LOG.error("Not path associated with listener sessionId: " + line + ", lastPath: "
+ lastPath);
}
} else {
// LOG.error("unrecognized line: " + line);
}
line = in.readLine();
}
break;
} catch (Exception e) {
// sometimes in test, we see connection-reset exceptions when in.readLine()
// so add this retry logic
retry--;
} finally {
if (sock != null) {
sock.close();
}
}
}
return listenerMap;
}
/**
* return a map from session-id to a set of zk-path that the session has watches on
* @return
*/
public static Map<String, Set<String>> getListenersBySession(String zkAddr) throws Exception {
Map<String, Set<String>> listenerMapByInstance = getListenersByZkPath(zkAddr);
// convert to index by sessionId
Map<String, Set<String>> listenerMapBySession = new TreeMap<>();
for (String path : listenerMapByInstance.keySet()) {
for (String sessionId : listenerMapByInstance.get(path)) {
if (!listenerMapBySession.containsKey(sessionId)) {
listenerMapBySession.put(sessionId, new TreeSet<String>());
}
listenerMapBySession.get(sessionId).add(path);
}
}
return listenerMapBySession;
}
static java.lang.reflect.Field getField(Class clazz, String fieldName)
throws NoSuchFieldException {
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
Class superClass = clazz.getSuperclass();
if (superClass == null) {
throw e;
} else {
return getField(superClass, fieldName);
}
}
}
public static Map<String, List<String>> getZkWatch(RealmAwareZkClient client) throws Exception {
Map<String, List<String>> lists = new HashMap<String, List<String>>();
ZkClient zkClient = (ZkClient) client;
ZkConnection connection = ((ZkConnection) zkClient.getConnection());
ZooKeeper zk = connection.getZookeeper();
java.lang.reflect.Field field = getField(zk.getClass(), "watchManager");
field.setAccessible(true);
Object watchManager = field.get(zk);
java.lang.reflect.Field field2 = getField(watchManager.getClass(), "dataWatches");
field2.setAccessible(true);
HashMap<String, Set<Watcher>> dataWatches =
(HashMap<String, Set<Watcher>>) field2.get(watchManager);
field2 = getField(watchManager.getClass(), "existWatches");
field2.setAccessible(true);
HashMap<String, Set<Watcher>> existWatches =
(HashMap<String, Set<Watcher>>) field2.get(watchManager);
field2 = getField(watchManager.getClass(), "childWatches");
field2.setAccessible(true);
HashMap<String, Set<Watcher>> childWatches =
(HashMap<String, Set<Watcher>>) field2.get(watchManager);
lists.put("dataWatches", new ArrayList<>(dataWatches.keySet()));
lists.put("existWatches", new ArrayList<>(existWatches.keySet()));
lists.put("childWatches", new ArrayList<>(childWatches.keySet()));
return lists;
}
public static Map<String, Set<IZkDataListener>> getZkDataListener(RealmAwareZkClient client)
throws Exception {
java.lang.reflect.Field field = getField(client.getClass(), "_dataListener");
field.setAccessible(true);
Map<String, Set<IZkDataListener>> dataListener =
(Map<String, Set<IZkDataListener>>) field.get(client);
return dataListener;
}
public static Map<String, Set<IZkChildListener>> getZkChildListener(RealmAwareZkClient client)
throws Exception {
java.lang.reflect.Field field = getField(client.getClass(), "_childListener");
field.setAccessible(true);
Map<String, Set<IZkChildListener>> childListener =
(Map<String, Set<IZkChildListener>>) field.get(client);
return childListener;
}
public static boolean tryWaitZkEventsCleaned(RealmAwareZkClient zkclient) throws Exception {
java.lang.reflect.Field field = getField(zkclient.getClass(), "_eventThread");
field.setAccessible(true);
Object eventThread = field.get(zkclient);
// System.out.println("field: " + eventThread);
java.lang.reflect.Field field2 = getField(eventThread.getClass(), "_events");
field2.setAccessible(true);
BlockingQueue queue = (BlockingQueue) field2.get(eventThread);
// System.out.println("field2: " + queue + ", " + queue.size());
if (queue == null) {
LOG.error("fail to get event-queue from zkclient. skip waiting");
return false;
}
for (int i = 0; i < 20; i++) {
if (queue.size() == 0) {
return true;
}
Thread.sleep(100);
System.out.println("pending zk-events in queue: " + queue);
}
return false;
}
public static void injectExpire(RealmAwareZkClient client)
throws ExecutionException, InterruptedException {
final ZkClient zkClient = (ZkClient) client;
Future future = _executor.submit(new Runnable() {
@Override
public void run() {
WatchedEvent event =
new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null);
zkClient.process(event);
}
});
future.get();
}
}
| 9,415 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestHelixTaskHandler.java
|
package org.apache.helix;
/*
* 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.PropertyKey.Builder;
import org.apache.helix.messaging.handling.HelixStateTransitionHandler;
import org.apache.helix.messaging.handling.HelixTask;
import org.apache.helix.messaging.handling.HelixTaskExecutor;
import org.apache.helix.mock.MockManager;
import org.apache.helix.mock.statemodel.MockMasterSlaveStateModel;
import org.apache.helix.mock.statemodel.MockStateModelAnnotated;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.tools.StateModelConfigGenerator;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class TestHelixTaskHandler {
@Test()
public void testInvocation() throws Exception {
HelixTaskExecutor executor = new HelixTaskExecutor();
System.out.println("START TestCMTaskHandler.testInvocation()");
Message message = new Message(MessageType.STATE_TRANSITION, "Some unique id");
message.setSrcName("cm-instance-0");
message.setTgtSessionId("1234");
message.setFromState("Offline");
message.setToState("Slave");
message.setPartitionName("TestDB_0");
message.setMsgId("Some unique message id");
message.setResourceName("TestDB");
message.setTgtName("localhost");
message.setStateModelDef("MasterSlave");
message.setStateModelFactoryName(HelixConstants.DEFAULT_STATE_MODEL_FACTORY);
MockMasterSlaveStateModel stateModel = new MockMasterSlaveStateModel();
NotificationContext context;
MockManager manager = new MockManager("clusterName");
HelixDataAccessor accessor = manager.getHelixDataAccessor();
StateModelDefinition stateModelDef =
new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave());
Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.stateModelDef("MasterSlave"), stateModelDef);
context = new NotificationContext(manager);
CurrentState currentStateDelta = new CurrentState("TestDB");
currentStateDelta.setState("TestDB_0", "OFFLINE");
HelixStateTransitionHandler stHandler =
new HelixStateTransitionHandler(null, stateModel, message, context, currentStateDelta);
HelixTask handler;
handler = new HelixTask(message, context, stHandler, executor);
handler.call();
AssertJUnit.assertTrue(stateModel.stateModelInvoked);
System.out.println("END TestCMTaskHandler.testInvocation() at "
+ new Date(System.currentTimeMillis()));
}
@Test()
public void testInvocationAnnotated() throws Exception {
System.out.println("START TestCMTaskHandler.testInvocationAnnotated() at "
+ new Date(System.currentTimeMillis()));
HelixTaskExecutor executor = new HelixTaskExecutor();
Message message = new Message(MessageType.STATE_TRANSITION, "Some unique id");
message.setSrcName("cm-instance-0");
message.setTgtSessionId("1234");
message.setFromState("Offline");
message.setToState("Slave");
message.setPartitionName("TestDB_0");
message.setMsgId("Some unique message id");
message.setResourceName("TestDB");
message.setTgtName("localhost");
message.setStateModelDef("MasterSlave");
message.setStateModelFactoryName(HelixConstants.DEFAULT_STATE_MODEL_FACTORY);
MockStateModelAnnotated stateModel = new MockStateModelAnnotated();
NotificationContext context;
MockManager manager = new MockManager("clusterName");
HelixDataAccessor accessor = manager.getHelixDataAccessor();
StateModelDefinition stateModelDef =
new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave());
Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.stateModelDef("MasterSlave"), stateModelDef);
context = new NotificationContext(manager);
CurrentState currentStateDelta = new CurrentState("TestDB");
currentStateDelta.setState("TestDB_0", "OFFLINE");
StateModelFactory<MockStateModelAnnotated> stateModelFactory =
new StateModelFactory<MockStateModelAnnotated>() {
@Override
public MockStateModelAnnotated createNewStateModel(String resource, String partitionName) {
// TODO Auto-generated method stub
return new MockStateModelAnnotated();
}
};
HelixStateTransitionHandler stHandler =
new HelixStateTransitionHandler(stateModelFactory, stateModel, message, context,
currentStateDelta);
HelixTask handler = new HelixTask(message, context, stHandler, executor);
handler.call();
AssertJUnit.assertTrue(stateModel.stateModelInvoked);
System.out.println("END TestCMTaskHandler.testInvocationAnnotated() at "
+ new Date(System.currentTimeMillis()));
}
}
| 9,416 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestZKRoutingInfoProvider.java
|
package org.apache.helix;
/*
* 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.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import org.apache.helix.controller.ExternalViewGenerator;
import org.apache.helix.model.CurrentState.CurrentStateProperty;
import org.apache.helix.model.Message;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
public class TestZKRoutingInfoProvider {
public Map<String, List<ZNRecord>> createCurrentStates(String[] dbNames, String[] nodeNames,
int[] partitions, int[] replicas) {
Map<String, List<ZNRecord>> currentStates = new TreeMap<String, List<ZNRecord>>();
Map<String, Map<String, ZNRecord>> currentStates2 =
new TreeMap<String, Map<String, ZNRecord>>();
Map<String, String> stateMaster = new TreeMap<String, String>();
stateMaster.put(CurrentStateProperty.CURRENT_STATE.name(), "MASTER");
Map<String, String> stateSlave = new TreeMap<String, String>();
stateSlave.put(CurrentStateProperty.CURRENT_STATE.name(), "SLAVE");
for (int i = 0; i < nodeNames.length; i++) {
currentStates.put(nodeNames[i], new ArrayList<ZNRecord>());
currentStates2.put(nodeNames[i], new TreeMap<String, ZNRecord>());
for (int j = 0; j < dbNames.length; j++) {
ZNRecord dbPartitionState = new ZNRecord(dbNames[j]);
currentStates2.get(nodeNames[i]).put(dbNames[j], dbPartitionState);
}
}
Random rand = new Random(1234);
for (int j = 0; j < dbNames.length; j++) {
int partition = partitions[j];
ArrayList<Integer> randomArray = new ArrayList<Integer>();
for (int i = 0; i < partition; i++) {
randomArray.add(i);
}
Collections.shuffle(randomArray, rand);
for (int i = 0; i < partition; i++) {
stateMaster.put(Message.Attributes.RESOURCE_NAME.toString(), dbNames[j]);
stateSlave.put(Message.Attributes.RESOURCE_NAME.toString(), dbNames[j]);
int nodes = nodeNames.length;
int master = randomArray.get(i) % nodes;
String partitionName = dbNames[j] + ".partition-" + i;
Map<String, Map<String, String>> map =
(currentStates2.get(nodeNames[master]).get(dbNames[j]).getMapFields());
assert (map != null);
map.put(partitionName, stateMaster);
for (int k = 1; k <= replicas[j]; k++) {
int slave = (master + k) % nodes;
Map<String, Map<String, String>> map2 =
currentStates2.get(nodeNames[slave]).get(dbNames[j]).getMapFields();
map2.put(partitionName, stateSlave);
}
}
}
for (String nodeName : currentStates2.keySet()) {
Map<String, ZNRecord> recMap = currentStates2.get(nodeName);
List<ZNRecord> list = new ArrayList<ZNRecord>();
for (ZNRecord rec : recMap.values()) {
list.add(rec);
}
currentStates.put(nodeName, list);
}
return currentStates;
}
private void verify(Map<String, List<ZNRecord>> currentStates,
Map<String, Map<String, Set<String>>> routingMap) {
int counter1 = 0;
int counter2 = 0;
for (String nodeName : currentStates.keySet()) {
List<ZNRecord> dbStateList = currentStates.get(nodeName);
for (ZNRecord dbState : dbStateList) {
Map<String, Map<String, String>> dbStateMap = dbState.getMapFields();
for (String partitionName : dbStateMap.keySet()) {
Map<String, String> stateMap = dbStateMap.get(partitionName);
String state = stateMap.get(CurrentStateProperty.CURRENT_STATE.name());
AssertJUnit.assertTrue(routingMap.get(partitionName).get(state).contains(nodeName));
counter1++;
}
}
}
for (String partitionName : routingMap.keySet()) {
Map<String, Set<String>> partitionState = routingMap.get(partitionName);
for (String state : partitionState.keySet()) {
counter2 += partitionState.get(state).size();
}
}
AssertJUnit.assertTrue(counter2 == counter1);
}
// public static void main(String[] args)
@Test()
public void testInvocation() throws Exception {
String[] dbNames = new String[3];
for (int i = 0; i < dbNames.length; i++) {
dbNames[i] = "DB_" + i;
}
String[] nodeNames = new String[6];
for (int i = 0; i < nodeNames.length; i++) {
nodeNames[i] = "LOCALHOST_100" + i;
}
int[] partitions = new int[dbNames.length];
for (int i = 0; i < partitions.length; i++) {
partitions[i] = (i + 1) * 10;
}
int[] replicas = new int[dbNames.length];
for (int i = 0; i < replicas.length; i++) {
replicas[i] = 3;
}
Map<String, List<ZNRecord>> currentStates =
createCurrentStates(dbNames, nodeNames, partitions, replicas);
ExternalViewGenerator provider = new ExternalViewGenerator();
List<ZNRecord> mockIdealStates = new ArrayList<ZNRecord>();
for (String dbName : dbNames) {
ZNRecord rec = new ZNRecord(dbName);
mockIdealStates.add(rec);
}
List<ZNRecord> externalView = provider.computeExternalView(currentStates, mockIdealStates);
Map<String, Map<String, Set<String>>> routingMap =
provider.getRouterMapFromExternalView(externalView);
verify(currentStates, routingMap);
/* write current state and external view to ZK */
/*
* String clusterName = "test-cluster44"; ZkClient zkClient = new
* ZkClient("localhost:2181"); zkClient.setZkSerializer(new
* ZNRecordSerializer());
* for(String nodeName : currentStates.keySet()) {
* if(zkClient.exists(CMUtil.getCurrentStatePath(clusterName, nodeName))) {
* zkClient.deleteRecursive(CMUtil.getCurrentStatePath(clusterName,
* nodeName)); } ZKUtil.createChildren(zkClient,CMUtil.getCurrentStatePath
* (clusterName, nodeName), currentStates.get(nodeName)); }
* //List<ZNRecord> externalView =
* ZKRoutingInfoProvider.computeExternalView(currentStates); String
* routingTablePath = CMUtil.getExternalViewPath(clusterName);
* if(zkClient.exists(routingTablePath)) {
* zkClient.deleteRecursive(routingTablePath); }
* ZKUtil.createChildren(zkClient, CMUtil.getExternalViewPath(clusterName),
* externalView);
*/
}
}
| 9,417 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestZNRecordBucketizer.java
|
package org.apache.helix;
/*
* 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.testng.Assert;
import org.testng.annotations.Test;
public class TestZNRecordBucketizer {
@Test
public void testZNRecordBucketizer() {
final int bucketSize = 3;
ZNRecordBucketizer bucketizer = new ZNRecordBucketizer(bucketSize);
String[] partitionNames = {
"TestDB_0", "TestDB_1", "TestDB_2", "TestDB_3", "TestDB_4"
};
for (int i = 0; i < partitionNames.length; i++) {
String partitionName = partitionNames[i];
String bucketName = bucketizer.getBucketName(partitionName);
int startBucketNb = i / bucketSize * bucketSize;
int endBucketNb = startBucketNb + bucketSize - 1;
String expectBucketName = "TestDB_p" + startBucketNb + "-p" + endBucketNb;
System.out.println("Expect: " + expectBucketName + ", actual: " + bucketName);
Assert.assertEquals(expectBucketName, bucketName);
}
// ZNRecord record = new ZNRecord("TestDB");
// record.setSimpleField("key0", "value0");
// record.setSimpleField("key1", "value1");
// record.setListField("TestDB_0", Arrays.asList("localhost_00", "localhost_01"));
// record.setListField("TestDB_1", Arrays.asList("localhost_10", "localhost_11"));
// record.setListField("TestDB_2", Arrays.asList("localhost_20", "localhost_21"));
// record.setListField("TestDB_3", Arrays.asList("localhost_30", "localhost_31"));
// record.setListField("TestDB_4", Arrays.asList("localhost_40", "localhost_41"));
//
// System.out.println(bucketizer.bucketize(record));
}
}
| 9,418 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestZkConnectionCount.java
|
package org.apache.helix;
/*
* 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.slf4j.Logger;
import org.slf4j.LoggerFactory;
// TODO fix this test
public class TestZkConnectionCount extends ZkUnitTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestZkConnectionCount.class);
// @Test ()
public void testZkConnectionCount() {
// ZkClient zkClient;
// int nrOfConn = ZkClient.getNumberOfConnections();
// System.out.println("Number of zk connections made " + nrOfConn);
//
// ZkConnection zkConn = new ZkConnection(ZK_ADDR);
//
// zkClient = new ZkClient(zkConn);
// AssertJUnit.assertEquals(nrOfConn + 1, ZkClient.getNumberOfConnections());
//
// zkClient = new ZkClient(ZK_ADDR);
// AssertJUnit.assertEquals(nrOfConn + 2, ZkClient.getNumberOfConnections());
//
// zkClient = ZKClientPool.getZkClient(ZK_ADDR);
// AssertJUnit.assertEquals(nrOfConn + 2, ZkClient.getNumberOfConnections());
}
}
| 9,419 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/ZkUnitTestBase.java
|
package org.apache.helix;
/*
* 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.common.ZkTestBase;
// TODO merge code with ZkIntegrationTestBase
public class ZkUnitTestBase extends ZkTestBase {
}
| 9,420 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/MockAccessor.java
|
package org.apache.helix;
/*
* 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.List;
import java.util.Map;
import org.apache.helix.mock.MockBaseDataAccessor;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.MaintenanceSignal;
import org.apache.helix.model.Message;
import org.apache.helix.model.PauseSignal;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.datamodel.ZNRecordUpdater;
import org.apache.helix.zookeeper.zkclient.DataUpdater;
import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException;
import org.apache.zookeeper.data.Stat;
public class MockAccessor implements HelixDataAccessor {
private final String _clusterName;
//Map<String, ZNRecord> data = new HashMap<String, ZNRecord>();
private final PropertyKey.Builder _propertyKeyBuilder;
private BaseDataAccessor _baseDataAccessor = new MockBaseDataAccessor();
public MockAccessor() {
this("testCluster-" + Math.random() * 10000 % 999);
}
public MockAccessor(String clusterName) {
_clusterName = clusterName;
_propertyKeyBuilder = new PropertyKey.Builder(_clusterName);
}
@Override
public boolean createStateModelDef(StateModelDefinition stateModelDef) {
return false;
}
@Override
public boolean createControllerMessage(Message message) {
return false;
}
@Override
public boolean createControllerLeader(LiveInstance leader) {
return false;
}
@Override
public boolean createPause(PauseSignal pauseSignal) {
return false;
}
@Override
public boolean createMaintenance(MaintenanceSignal maintenanceSignal) {
return false;
}
@Override
public boolean setProperty(PropertyKey key, HelixProperty value) {
String path = key.getPath();
_baseDataAccessor.set(path, value.getRecord(), AccessOption.PERSISTENT);
return true;
}
@Override
public <T extends HelixProperty> boolean updateProperty(PropertyKey key, T value) {
return updateProperty(key, new ZNRecordUpdater(value.getRecord()), value);
}
@Override
public <T extends HelixProperty> boolean updateProperty(PropertyKey key,
DataUpdater<ZNRecord> updater, T value) {
String path = key.getPath();
PropertyType type = key.getType();
if (type.updateOnlyOnExists) {
if (_baseDataAccessor.exists(path, 0)) {
if (type.mergeOnUpdate) {
ZNRecord znRecord = new ZNRecord((ZNRecord) _baseDataAccessor.get(path, null, 0));
ZNRecord newZNRecord = updater.update(znRecord);
if (newZNRecord != null) {
_baseDataAccessor.set(path, newZNRecord, 0);
}
} else {
_baseDataAccessor.set(path, value.getRecord(), 0);
}
}
} else {
if (type.mergeOnUpdate) {
if (_baseDataAccessor.exists(path, 0)) {
ZNRecord znRecord = new ZNRecord((ZNRecord) _baseDataAccessor.get(path, null, 0));
ZNRecord newZNRecord = updater.update(znRecord);
if (newZNRecord != null) {
_baseDataAccessor.set(path, newZNRecord, 0);
}
} else {
_baseDataAccessor.set(path, value.getRecord(), 0);
}
} else {
_baseDataAccessor.set(path, value.getRecord(), 0);
}
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public <T extends HelixProperty> T getProperty(PropertyKey key) {
String path = key.getPath();
Stat stat = new Stat();
return (T) HelixProperty.convertToTypedInstance(key.getTypeClass(),
(ZNRecord) _baseDataAccessor.get(path, stat, 0));
}
@Override
public boolean removeProperty(PropertyKey key) {
String path = key.getPath(); // PropertyPathConfig.getPath(type,
// _clusterName, keys);
_baseDataAccessor.remove(path, 0);
return true;
}
@Override
public HelixProperty.Stat getPropertyStat(PropertyKey key) {
PropertyType type = key.getType();
String path = key.getPath();
try {
Stat stat = _baseDataAccessor.getStat(path, 0);
if (stat != null) {
return new HelixProperty.Stat(stat.getVersion(), stat.getCtime(), stat.getMtime(),
stat.getEphemeralOwner());
}
} catch (ZkNoNodeException e) {
}
return null;
}
@Override
public List<HelixProperty.Stat> getPropertyStats(List<PropertyKey> keys) {
if (keys == null || keys.size() == 0) {
return Collections.emptyList();
}
List<HelixProperty.Stat> propertyStats = new ArrayList<>(keys.size());
List<String> paths = new ArrayList<>(keys.size());
for (PropertyKey key : keys) {
paths.add(key.getPath());
}
Stat[] zkStats = _baseDataAccessor.getStats(paths, 0);
for (int i = 0; i < keys.size(); i++) {
Stat zkStat = zkStats[i];
HelixProperty.Stat propertyStat = null;
if (zkStat != null) {
propertyStat =
new HelixProperty.Stat(zkStat.getVersion(), zkStat.getCtime(), zkStat.getMtime(),
zkStat.getEphemeralOwner());
}
propertyStats.add(propertyStat);
}
return propertyStats;
}
@Override
public List<String> getChildNames(PropertyKey propertyKey) {
String path = propertyKey.getPath();
return _baseDataAccessor.getChildNames(path, 0);
}
@SuppressWarnings("unchecked")
@Deprecated
@Override
public <T extends HelixProperty> List<T> getChildValues(PropertyKey propertyKey) {
return getChildValues(propertyKey, false);
}
@Override
public <T extends HelixProperty> List<T> getChildValues(PropertyKey key, boolean throwException) {
String path = key.getPath(); // PropertyPathConfig.getPath(type,
List<ZNRecord> children = _baseDataAccessor.getChildren(path, null, 0, 0, 0);
return (List<T>) HelixProperty.convertToTypedList(key.getTypeClass(), children);
}
@Deprecated
@Override
public <T extends HelixProperty> Map<String, T> getChildValuesMap(PropertyKey key) {
return getChildValuesMap(key, false);
}
@Override
public <T extends HelixProperty> Map<String, T> getChildValuesMap(PropertyKey key,
boolean throwException) {
List<T> list = getChildValues(key, throwException);
return HelixProperty.convertListToMap(list);
}
@Override
public <T extends HelixProperty> boolean[] createChildren(List<PropertyKey> keys,
List<T> children) {
return setChildren(keys, children);
}
@Override
public <T extends HelixProperty> boolean[] setChildren(List<PropertyKey> keys, List<T> children) {
boolean[] results = new boolean[keys.size()];
for (int i = 0; i < keys.size(); i++) {
results[i] = setProperty(keys.get(i), children.get(i));
}
return results;
}
@Override
public PropertyKey.Builder keyBuilder() {
return _propertyKeyBuilder;
}
@Override
public BaseDataAccessor getBaseDataAccessor() {
return _baseDataAccessor;
}
@Override
public <T extends HelixProperty> boolean[] updateChildren(List<String> paths,
List<DataUpdater<ZNRecord>> updaters, int options) {
return _baseDataAccessor.updateChildren(paths, updaters, options);
}
@Deprecated
@Override
public <T extends HelixProperty> List<T> getProperty(List<PropertyKey> keys) {
return getProperty(keys, false);
}
@Override
public <T extends HelixProperty> List<T> getProperty(List<PropertyKey> keys,
boolean throwException) {
List<T> list = new ArrayList<T>();
for (PropertyKey key : keys) {
@SuppressWarnings("unchecked")
T t = (T) getProperty(key);
list.add(t);
}
return list;
}
}
| 9,421 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestZnodeModify.java
|
package org.apache.helix;
/*
* 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.model.IdealState.IdealStateProperty;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.TestCommand;
import org.apache.helix.tools.TestCommand.CommandType;
import org.apache.helix.tools.TestExecutor;
import org.apache.helix.tools.TestExecutor.ZnodePropertyType;
import org.apache.helix.tools.TestTrigger;
import org.apache.helix.tools.ZnodeOpArg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestZnodeModify extends ZkUnitTestBase {
private static Logger logger = LoggerFactory.getLogger(TestZnodeModify.class);
private final String PREFIX = "/" + getShortClassName();
@Test()
public void testBasic() throws Exception {
logger.info("RUN: " + new Date(System.currentTimeMillis()));
List<TestCommand> commandList = new ArrayList<>();
// test case for the basic flow, no timeout, no data trigger
String pathChild1 = PREFIX + "/basic_child1";
String pathChild2 = PREFIX + "/basic_child2";
TestCommand command;
ZnodeOpArg arg;
arg = new ZnodeOpArg(pathChild1, ZnodePropertyType.SIMPLE, "+", "key1", "simpleValue1");
command = new TestCommand(CommandType.MODIFY, arg);
commandList.add(command);
List<String> list = new ArrayList<>();
list.add("listValue1");
list.add("listValue2");
arg = new ZnodeOpArg(pathChild1, ZnodePropertyType.LIST, "+", "key2", list);
command = new TestCommand(CommandType.MODIFY, arg);
commandList.add(command);
ZNRecord record = getExampleZNRecord();
arg = new ZnodeOpArg(pathChild2, ZnodePropertyType.ZNODE, "+", record);
command = new TestCommand(CommandType.MODIFY, arg);
commandList.add(command);
arg = new ZnodeOpArg(pathChild1, ZnodePropertyType.SIMPLE, "==", "key1");
command = new TestCommand(CommandType.VERIFY, new TestTrigger(1000, 0, "simpleValue1"), arg);
commandList.add(command);
arg = new ZnodeOpArg(pathChild1, ZnodePropertyType.LIST, "==", "key2");
command = new TestCommand(CommandType.VERIFY, new TestTrigger(1000, 0, list), arg);
commandList.add(command);
arg = new ZnodeOpArg(pathChild2, ZnodePropertyType.ZNODE, "==");
command = new TestCommand(CommandType.VERIFY, new TestTrigger(1000, 0, record), arg);
commandList.add(command);
Map<TestCommand, Boolean> results = TestExecutor.executeTest(commandList, ZK_ADDR);
for (Map.Entry<TestCommand, Boolean> entry : results.entrySet()) {
Assert.assertTrue(entry.getValue());
}
logger.info("END: " + new Date(System.currentTimeMillis()));
}
@Test()
public void testDataTrigger() throws Exception {
logger.info("RUN: " + new Date(System.currentTimeMillis()));
List<TestCommand> commandList = new ArrayList<>();
// test case for data trigger, no timeout
String pathChild1 = PREFIX + "/data_trigger_child1";
String pathChild2 = PREFIX + "/data_trigger_child2";
ZnodeOpArg arg;
TestCommand command;
ZnodeOpArg arg1 =
new ZnodeOpArg(pathChild1, ZnodePropertyType.SIMPLE, "+", "key1", "simpleValue1-new");
TestCommand command1 =
new TestCommand(CommandType.MODIFY, new TestTrigger(0, 0, "simpleValue1"), arg1);
commandList.add(command1);
ZNRecord record = getExampleZNRecord();
ZNRecord recordNew = new ZNRecord(record);
recordNew.setSimpleField(IdealStateProperty.REBALANCE_MODE.toString(),
RebalanceMode.SEMI_AUTO.toString());
arg = new ZnodeOpArg(pathChild2, ZnodePropertyType.ZNODE, "+", recordNew);
command = new TestCommand(CommandType.MODIFY, new TestTrigger(0, 3000, record), arg);
commandList.add(command);
arg = new ZnodeOpArg(pathChild2, ZnodePropertyType.ZNODE, "+", record);
command = new TestCommand(CommandType.MODIFY, new TestTrigger(1000), arg);
commandList.add(command);
arg = new ZnodeOpArg(pathChild1, ZnodePropertyType.SIMPLE, "!=", "key1");
command =
new TestCommand(CommandType.VERIFY, new TestTrigger(3100, 0, "simpleValue1-new"), arg);
commandList.add(command);
arg = new ZnodeOpArg(pathChild2, ZnodePropertyType.ZNODE, "==");
command = new TestCommand(CommandType.VERIFY, new TestTrigger(3100, 0, recordNew), arg);
commandList.add(command);
Map<TestCommand, Boolean> results = TestExecutor.executeTest(commandList, ZK_ADDR);
boolean result = results.remove(command1);
AssertJUnit.assertFalse(result);
for (Map.Entry<TestCommand, Boolean> entry : results.entrySet()) {
Assert.assertTrue(entry.getValue());
}
logger.info("END: " + new Date(System.currentTimeMillis()));
}
@Test()
public void testTimeout() throws Exception {
logger.info("RUN: " + new Date(System.currentTimeMillis()));
List<TestCommand> commandList = new ArrayList<>();
// test case for timeout, no data trigger
String pathChild1 = PREFIX + "/timeout_child1";
String pathChild2 = PREFIX + "/timeout_child2";
ZnodeOpArg arg1 =
new ZnodeOpArg(pathChild1, ZnodePropertyType.SIMPLE, "+", "key1", "simpleValue1-new");
TestCommand command1 =
new TestCommand(CommandType.MODIFY, new TestTrigger(0, 1000, "simpleValue1"), arg1);
commandList.add(command1);
ZNRecord record = getExampleZNRecord();
ZNRecord recordNew = new ZNRecord(record);
recordNew.setSimpleField(IdealStateProperty.REBALANCE_MODE.toString(),
RebalanceMode.SEMI_AUTO.toString());
arg1 = new ZnodeOpArg(pathChild2, ZnodePropertyType.ZNODE, "+", recordNew);
command1 = new TestCommand(CommandType.MODIFY, new TestTrigger(0, 500, record), arg1);
commandList.add(command1);
arg1 = new ZnodeOpArg(pathChild1, ZnodePropertyType.SIMPLE, "==", "key1");
command1 =
new TestCommand(CommandType.VERIFY, new TestTrigger(1000, 500, "simpleValue1-new"), arg1);
commandList.add(command1);
arg1 = new ZnodeOpArg(pathChild1, ZnodePropertyType.ZNODE, "==");
command1 = new TestCommand(CommandType.VERIFY, new TestTrigger(1000, 500, recordNew), arg1);
commandList.add(command1);
Map<TestCommand, Boolean> results = TestExecutor.executeTest(commandList, ZK_ADDR);
for (Map.Entry<TestCommand, Boolean> entry : results.entrySet()) {
Assert.assertFalse(entry.getValue());
}
logger.info("END: " + new Date(System.currentTimeMillis()));
}
@Test()
public void testDataTriggerWithTimeout() throws Exception {
logger.info("RUN: " + new Date(System.currentTimeMillis()));
List<TestCommand> commandList = new ArrayList<>();
// test case for data trigger with timeout
final String pathChild1 = PREFIX + "/dataTriggerWithTimeout_child1";
final ZNRecord record = getExampleZNRecord();
ZNRecord recordNew = new ZNRecord(record);
recordNew.setSimpleField(IdealStateProperty.REBALANCE_MODE.toString(),
RebalanceMode.SEMI_AUTO.toString());
ZnodeOpArg arg1 = new ZnodeOpArg(pathChild1, ZnodePropertyType.ZNODE, "+", recordNew);
TestCommand command1 =
new TestCommand(CommandType.MODIFY, new TestTrigger(0, 8000, record), arg1);
commandList.add(command1);
arg1 = new ZnodeOpArg(pathChild1, ZnodePropertyType.ZNODE, "==");
command1 = new TestCommand(CommandType.VERIFY, new TestTrigger(9000, 500, recordNew), arg1);
commandList.add(command1);
// start a separate thread to change znode at pathChild1
new Thread(() -> {
try {
Thread.sleep(3000);
_gZkClient.createPersistent(pathChild1, true);
_gZkClient.writeData(pathChild1, record);
} catch (InterruptedException e) {
logger.error("Interrupted sleep", e);
}
}).start();
Map<TestCommand, Boolean> results = TestExecutor.executeTest(commandList, ZK_ADDR);
for (Map.Entry<TestCommand, Boolean> entry : results.entrySet()) {
Assert.assertTrue(entry.getValue());
}
}
@BeforeClass()
public void beforeClass() {
System.out
.println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
if (_gZkClient.exists(PREFIX)) {
_gZkClient.deleteRecursively(PREFIX);
}
}
@AfterClass
public void afterClass() {
if (_gZkClient.exists(PREFIX)) {
_gZkClient.deleteRecursively(PREFIX);
}
System.out
.println("END " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
}
private ZNRecord getExampleZNRecord() {
ZNRecord record = new ZNRecord("TestDB");
record.setSimpleField(IdealStateProperty.REBALANCE_MODE.toString(),
RebalanceMode.CUSTOMIZED.toString());
Map<String, String> map = new HashMap<>();
map.put("localhost_12918", "MASTER");
map.put("localhost_12919", "SLAVE");
record.setMapField("TestDB_0", map);
List<String> list = new ArrayList<>();
list.add("localhost_12918");
list.add("localhost_12919");
record.setListField("TestDB_0", list);
return record;
}
}
| 9,422 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestShuffledIdealState.java
|
package org.apache.helix;
/*
* 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.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.helix.tools.IdealCalculatorByConsistentHashing;
import org.apache.helix.tools.IdealStateCalculatorByRush;
import org.apache.helix.tools.IdealStateCalculatorByShuffling;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.introspect.CodehausJacksonIntrospector;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class TestShuffledIdealState {
@Test()
public void testInvocation() throws Exception {
int partitions = 6, replicas = 2;
String dbName = "espressoDB1";
List<String> instanceNames = new ArrayList<String>();
instanceNames.add("localhost_1231");
instanceNames.add("localhost_1232");
instanceNames.add("localhost_1233");
instanceNames.add("localhost_1234");
ZNRecord result = IdealStateCalculatorByShuffling
.calculateIdealState(instanceNames, partitions, replicas, dbName);
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE");
ZNRecord result2 = IdealStateCalculatorByRush
.calculateIdealState(instanceNames, 1, partitions, replicas, dbName);
ZNRecord result3 = IdealCalculatorByConsistentHashing
.calculateIdealState(instanceNames, partitions, replicas, dbName,
new IdealCalculatorByConsistentHashing.FnvHash());
IdealCalculatorByConsistentHashing.printIdealStateStats(result3, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result3, "SLAVE");
IdealCalculatorByConsistentHashing.printIdealStateStats(result3, "");
IdealCalculatorByConsistentHashing.printNodeOfflineOverhead(result3);
// System.out.println(result);
ObjectMapper mapper =
new ObjectMapper().setAnnotationIntrospector(new CodehausJacksonIntrospector());
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, result);
// System.out.println(sw.toString());
ZNRecord zn = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class);
System.out.println(result.toString());
System.out.println(zn.toString());
AssertJUnit.assertTrue(zn.toString().equalsIgnoreCase(result.toString()));
System.out.println();
sw = new StringWriter();
mapper.writeValue(sw, result2);
ZNRecord zn2 = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class);
System.out.println(result2.toString());
System.out.println(zn2.toString());
AssertJUnit.assertTrue(zn2.toString().equalsIgnoreCase(result2.toString()));
sw = new StringWriter();
mapper.writeValue(sw, result3);
System.out.println();
ZNRecord zn3 = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class);
System.out.println(result3.toString());
System.out.println(zn3.toString());
AssertJUnit.assertTrue(zn3.toString().equalsIgnoreCase(result3.toString()));
System.out.println();
}
@Test
public void testShuffledIdealState() {
// partitions is larger than nodes
int partitions = 6, replicas = 2, instances = 4;
String dbName = "espressoDB1";
List<String> instanceNames = new ArrayList<String>();
instanceNames.add("localhost_1231");
instanceNames.add("localhost_1232");
instanceNames.add("localhost_1233");
instanceNames.add("localhost_1234");
ZNRecord result = IdealStateCalculatorByShuffling
.calculateIdealState(instanceNames, partitions, replicas, dbName);
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE");
Assert.assertTrue(verify(result));
// partition is less than nodes
instanceNames.clear();
partitions = 4;
replicas = 3;
instances = 7;
for (int i = 0; i < instances; i++) {
instanceNames.add("localhost_" + (1231 + i));
}
result = IdealStateCalculatorByShuffling
.calculateIdealState(instanceNames, partitions, replicas, dbName);
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE");
Assert.assertTrue(verify(result));
// partitions is multiple of nodes
instanceNames.clear();
partitions = 14;
replicas = 3;
instances = 7;
for (int i = 0; i < instances; i++) {
instanceNames.add("localhost_" + (1231 + i));
}
result = IdealStateCalculatorByShuffling
.calculateIdealState(instanceNames, partitions, replicas, dbName);
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE");
Assert.assertTrue(verify(result));
// nodes are multiple of partitions
instanceNames.clear();
partitions = 4;
replicas = 3;
instances = 8;
for (int i = 0; i < instances; i++) {
instanceNames.add("localhost_" + (1231 + i));
}
result = IdealStateCalculatorByShuffling
.calculateIdealState(instanceNames, partitions, replicas, dbName);
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE");
Assert.assertTrue(verify(result));
// nodes are multiple of partitions
instanceNames.clear();
partitions = 4;
replicas = 3;
instances = 12;
for (int i = 0; i < instances; i++) {
instanceNames.add("localhost_" + (1231 + i));
}
result = IdealStateCalculatorByShuffling
.calculateIdealState(instanceNames, partitions, replicas, dbName);
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE");
Assert.assertTrue(verify(result));
// Just fits
instanceNames.clear();
partitions = 4;
replicas = 2;
instances = 12;
for (int i = 0; i < instances; i++) {
instanceNames.add("localhost_" + (1231 + i));
}
result = IdealStateCalculatorByShuffling
.calculateIdealState(instanceNames, partitions, replicas, dbName);
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "MASTER");
IdealCalculatorByConsistentHashing.printIdealStateStats(result, "SLAVE");
Assert.assertTrue(verify(result));
}
boolean verify(ZNRecord result) {
Map<String, Integer> masterPartitionCounts = new HashMap<String, Integer>();
Map<String, Integer> slavePartitionCounts = new HashMap<String, Integer>();
for (String key : result.getMapFields().keySet()) {
Map<String, String> mapField = result.getMapField(key);
int masterCount = 0;
for (String host : mapField.keySet()) {
if (mapField.get(host).equals("MASTER")) {
Assert.assertTrue(masterCount == 0);
masterCount++;
if (!masterPartitionCounts.containsKey(host)) {
masterPartitionCounts.put(host, 0);
} else {
masterPartitionCounts.put(host, masterPartitionCounts.get(host) + 1);
}
} else {
if (!slavePartitionCounts.containsKey(host)) {
slavePartitionCounts.put(host, 0);
} else {
slavePartitionCounts.put(host, slavePartitionCounts.get(host) + 1);
}
}
}
}
List<Integer> masterCounts = new ArrayList<Integer>();
List<Integer> slaveCounts = new ArrayList<Integer>();
masterCounts.addAll(masterPartitionCounts.values());
slaveCounts.addAll(slavePartitionCounts.values());
Collections.sort(masterCounts);
Collections.sort(slaveCounts);
Assert.assertTrue(masterCounts.get(masterCounts.size() - 1) - masterCounts.get(0) <= 1);
Assert.assertTrue(slaveCounts.get(slaveCounts.size() - 1) - slaveCounts.get(0) <= 2);
return true;
}
}
| 9,423 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestHelixConfigAccessor.java
|
package org.apache.helix;
/*
* 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.manager.zk.ZKHelixAdmin;
import org.apache.helix.model.HelixConfigScope;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.builder.HelixConfigScopeBuilder;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestHelixConfigAccessor extends ZkUnitTestBase {
@Test
public void testBasic() 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, "localhost", "TestDB", 1, 10, 5, 3,
"MasterSlave", true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
HelixConfigScope clusterScope =
new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(clusterName).build();
// cluster scope config
String clusterConfigValue = configAccessor.get(clusterScope, "clusterConfigKey");
Assert.assertNull(clusterConfigValue);
configAccessor.set(clusterScope, "clusterConfigKey", "clusterConfigValue");
clusterConfigValue = configAccessor.get(clusterScope, "clusterConfigKey");
Assert.assertEquals(clusterConfigValue, "clusterConfigValue");
// resource scope config
HelixConfigScope resourceScope =
new HelixConfigScopeBuilder(ConfigScopeProperty.RESOURCE).forCluster(clusterName)
.forResource("testResource").build();
configAccessor.set(resourceScope, "resourceConfigKey", "resourceConfigValue");
String resourceConfigValue = configAccessor.get(resourceScope, "resourceConfigKey");
Assert.assertEquals(resourceConfigValue, "resourceConfigValue");
// partition scope config
HelixConfigScope partitionScope =
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTITION).forCluster(clusterName)
.forResource("testResource").forPartition("testPartition").build();
configAccessor.set(partitionScope, "partitionConfigKey", "partitionConfigValue");
String partitionConfigValue = configAccessor.get(partitionScope, "partitionConfigKey");
Assert.assertEquals(partitionConfigValue, "partitionConfigValue");
// participant scope config
HelixConfigScope participantScope =
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTICIPANT).forCluster(clusterName)
.forParticipant("localhost_12918").build();
configAccessor.set(participantScope, "participantConfigKey", "participantConfigValue");
String participantConfigValue = configAccessor.get(participantScope, "participantConfigKey");
Assert.assertEquals(participantConfigValue, "participantConfigValue");
// test get-keys
List<String> keys =
configAccessor.getKeys(new HelixConfigScopeBuilder(ConfigScopeProperty.RESOURCE)
.forCluster(clusterName).build());
Assert.assertEquals(keys.size(), 1, "should be [testResource]");
Assert.assertEquals(keys.get(0), "testResource");
// keys = configAccessor.getKeys(new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER)
// .forCluster(clusterName)
// .build());
// Assert.assertEquals(keys.size(), 1, "should be [" + clusterName + "]");
// Assert.assertEquals(keys.get(0), clusterName);
keys =
configAccessor.getKeys(new HelixConfigScopeBuilder(ConfigScopeProperty.PARTICIPANT)
.forCluster(clusterName).build());
Assert.assertEquals(keys.size(), 5, "should be [localhost_12918~22] sorted");
Assert.assertTrue(keys.contains("localhost_12918"));
Assert.assertTrue(keys.contains("localhost_12922"));
keys =
configAccessor.getKeys(new HelixConfigScopeBuilder(ConfigScopeProperty.PARTITION)
.forCluster(clusterName).forResource("testResource").build());
Assert.assertEquals(keys.size(), 1, "should be [testPartition]");
Assert.assertEquals(keys.get(0), "testPartition");
keys =
configAccessor.getKeys(new HelixConfigScopeBuilder(ConfigScopeProperty.RESOURCE)
.forCluster(clusterName).forResource("testResource").build());
Assert.assertEquals(keys.size(), 1, "should be [resourceConfigKey]");
Assert.assertTrue(keys.contains("resourceConfigKey"));
keys = configAccessor.getKeys(
new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(clusterName).build());
Assert.assertEquals(keys.size(), 1, "should be [clusterConfigKey]");
Assert.assertTrue(keys.contains("clusterConfigKey"));
keys = configAccessor.getKeys(
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTICIPANT).forCluster(clusterName)
.forParticipant("localhost_12918").build());
Assert.assertEquals(keys.size(), 3, "should be [HELIX_PORT, HELIX_HOST, participantConfigKey]");
Assert.assertTrue(keys.contains("participantConfigKey"));
keys = configAccessor.getKeys(
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTITION).forCluster(clusterName)
.forResource("testResource").forPartition("testPartition").build());
Assert.assertEquals(keys.size(), 1, "should be [partitionConfigKey]");
Assert.assertEquals(keys.get(0), "partitionConfigKey");
// test configAccessor.remove
configAccessor.remove(clusterScope, "clusterConfigKey");
clusterConfigValue = configAccessor.get(clusterScope, "clusterConfigKey");
Assert.assertNull(clusterConfigValue, "Should be null since it's removed");
configAccessor.remove(resourceScope, "resourceConfigKey");
resourceConfigValue = configAccessor.get(resourceScope, "resourceConfigKey");
Assert.assertNull(resourceConfigValue, "Should be null since it's removed");
configAccessor.remove(partitionScope, "partitionConfigKey");
partitionConfigValue = configAccessor.get(partitionScope, "partitionConfigKey");
Assert.assertNull(partitionConfigValue, "Should be null since it's removed");
configAccessor.remove(participantScope, "participantConfigKey");
participantConfigValue = configAccessor.get(partitionScope, "participantConfigKey");
Assert.assertNull(participantConfigValue, "Should be null since it's removed");
// negative tests
try {
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTITION).forPartition("testPartition")
.build();
Assert.fail("Should fail since cluster name is not set");
} catch (Exception e) {
// OK
}
try {
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTICIPANT)
.forParticipant("testParticipant").build();
Assert.fail("Should fail since cluster name is not set");
} catch (Exception e) {
// OK
}
try {
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTITION).forCluster("testCluster")
.forPartition("testPartition").build();
Assert.fail("Should fail since resource name is not set");
} catch (Exception e) {
// OK
// e.printStackTrace();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
// HELIX-25: set participant Config should check existence of instance
@Test
public void testSetNonexistentParticipantConfig() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
ZKHelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.addCluster(clusterName, true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
HelixConfigScope participantScope =
new HelixConfigScopeBuilder(ConfigScopeProperty.PARTICIPANT).forCluster(clusterName)
.forParticipant("localhost_12918").build();
try {
configAccessor.set(participantScope, "participantConfigKey", "participantConfigValue");
Assert
.fail("Except fail to set participant-config because participant: localhost_12918 is not added to cluster yet");
} catch (HelixException e) {
// OK
}
admin.addInstance(clusterName, new InstanceConfig("localhost_12918"));
try {
configAccessor.set(participantScope, "participantConfigKey", "participantConfigValue");
} catch (Exception e) {
Assert
.fail("Except succeed to set participant-config because participant: localhost_12918 has been added to cluster");
}
String participantConfigValue = configAccessor.get(participantScope, "participantConfigKey");
Assert.assertEquals(participantConfigValue, "participantConfigValue");
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,424 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestRoutingTable.java
|
package org.apache.helix;
/*
* 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.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.helix.mock.MockManager;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.spectator.RoutingTableProvider;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestRoutingTable {
NotificationContext changeContext = null;
@BeforeClass()
public synchronized void setup() {
final String[] array = new String[] {
"localhost_8900", "localhost_8901"
};
HelixManager manager = new MockManager() {
private MockAccessor _mockAccessor;
@Override
// public DataAccessor getDataAccessor()
public HelixDataAccessor getHelixDataAccessor() {
if (_mockAccessor == null) {
_mockAccessor = new MockAccessor() {
@SuppressWarnings("unchecked")
@Override
public <T extends HelixProperty> List<T> getChildValues(PropertyKey key,
boolean throwException) {
PropertyType type = key.getType();
String[] keys = key.getParams();
if (type == PropertyType.CONFIGS && keys != null && keys.length > 1 && keys[1]
.equalsIgnoreCase(ConfigScopeProperty.PARTICIPANT.toString())) {
List<InstanceConfig> configs = new ArrayList<InstanceConfig>();
for (String instanceName : array) {
InstanceConfig config = new InstanceConfig(instanceName);
String[] splits = instanceName.split("_");
config.setHostName(splits[0]);
config.setPort(splits[1]);
configs.add(config);
}
return (List<T>) configs;
}
return Collections.emptyList();
}
};
}
return _mockAccessor;
}
};
changeContext = new NotificationContext(manager);
}
@Test()
public void testNullAndEmpty() {
RoutingTableProvider routingTable = new RoutingTableProvider();
try {
routingTable.onExternalViewChange(null, changeContext);
List<ExternalView> list = Collections.emptyList();
routingTable.onExternalViewChange(list, changeContext);
} finally {
routingTable.shutdown();
}
}
@Test()
public void testSimple() {
List<InstanceConfig> instances;
RoutingTableProvider routingTable = new RoutingTableProvider();
ZNRecord record = new ZNRecord("TESTDB");
try {
// one master
add(record, "TESTDB_0", "localhost_8900", "MASTER");
List<ExternalView> externalViewList = new ArrayList<>();
externalViewList.add(new ExternalView(record));
routingTable.onExternalViewChange(externalViewList, changeContext);
instances = routingTable.getInstances("TESTDB", "TESTDB_0", "MASTER");
AssertJUnit.assertNotNull(instances);
AssertJUnit.assertEquals(instances.size(), 1);
// additions
add(record, "TESTDB_0", "localhost_8901", "MASTER");
add(record, "TESTDB_1", "localhost_8900", "SLAVE");
externalViewList = new ArrayList<ExternalView>();
externalViewList.add(new ExternalView(record));
routingTable.onExternalViewChange(externalViewList, changeContext);
instances = routingTable.getInstances("TESTDB", "TESTDB_0", "MASTER");
AssertJUnit.assertNotNull(instances);
AssertJUnit.assertEquals(instances.size(), 2);
instances = routingTable.getInstances("TESTDB", "TESTDB_1", "SLAVE");
AssertJUnit.assertNotNull(instances);
AssertJUnit.assertEquals(instances.size(), 1);
// updates
add(record, "TESTDB_0", "localhost_8901", "SLAVE");
externalViewList = new ArrayList<>();
externalViewList.add(new ExternalView(record));
routingTable.onExternalViewChange(externalViewList, changeContext);
instances = routingTable.getInstances("TESTDB", "TESTDB_0", "SLAVE");
AssertJUnit.assertNotNull(instances);
AssertJUnit.assertEquals(instances.size(), 1);
} finally {
routingTable.shutdown();
}
}
@Test()
public void testGetResources() {
RoutingTableProvider routingTable = new RoutingTableProvider();
List<ExternalView> externalViewList = new ArrayList<>();
Set<String> databases = new HashSet<>();
try {
for (int i = 0; i < 5; i++) {
String db = "TESTDB" + i;
ZNRecord record = new ZNRecord(db);
// one master
add(record, db + "_0", "localhost_8900", "MASTER");
add(record, db + "_1", "localhost_8901", "SLAVE");
externalViewList.add(new ExternalView(record));
databases.add(db);
}
routingTable.onExternalViewChange(externalViewList, changeContext);
Collection<String> resources = routingTable.getResources();
Assert.assertEquals(databases.size(), externalViewList.size());
Assert.assertEquals(databases, new HashSet<>(resources));
} finally {
routingTable.shutdown();
}
}
@Test()
public void testStateUnitGroupDeletion() throws InterruptedException {
List<InstanceConfig> instances;
RoutingTableProvider routingTable = new RoutingTableProvider();
try {
List<ExternalView> externalViewList = new ArrayList<ExternalView>();
ZNRecord record = new ZNRecord("TESTDB");
// one master
add(record, "TESTDB_0", "localhost_8900", "MASTER");
externalViewList.add(new ExternalView(record));
externalViewList.add(new ExternalView(new ZNRecord("fake")));
routingTable.onExternalViewChange(externalViewList, changeContext);
instances = routingTable.getInstances("TESTDB", "TESTDB_0", "MASTER");
AssertJUnit.assertNotNull(instances);
AssertJUnit.assertEquals(instances.size(), 1);
externalViewList.remove(0);
routingTable.onExternalViewChange(externalViewList, changeContext);
Thread.sleep(100);
instances = routingTable.getInstances("TESTDB", "TESTDB_0", "MASTER");
AssertJUnit.assertNotNull(instances);
AssertJUnit.assertEquals(instances.size(), 0);
} finally {
routingTable.shutdown();
}
}
@Test()
public void testGetInstanceForAllStateUnits() {
List<InstanceConfig> instancesList;
Set<InstanceConfig> instancesSet;
InstanceConfig instancesArray[];
RoutingTableProvider routingTable = new RoutingTableProvider();
try {
List<ExternalView> externalViewList = new ArrayList<ExternalView>();
ZNRecord record = new ZNRecord("TESTDB");
// one master
add(record, "TESTDB_0", "localhost_8900", "MASTER");
add(record, "TESTDB_1", "localhost_8900", "MASTER");
add(record, "TESTDB_2", "localhost_8900", "MASTER");
add(record, "TESTDB_3", "localhost_8900", "SLAVE");
add(record, "TESTDB_4", "localhost_8900", "SLAVE");
add(record, "TESTDB_5", "localhost_8900", "SLAVE");
add(record, "TESTDB_0", "localhost_8901", "SLAVE");
add(record, "TESTDB_1", "localhost_8901", "SLAVE");
add(record, "TESTDB_2", "localhost_8901", "SLAVE");
add(record, "TESTDB_3", "localhost_8901", "MASTER");
add(record, "TESTDB_4", "localhost_8901", "MASTER");
add(record, "TESTDB_5", "localhost_8901", "MASTER");
externalViewList.add(new ExternalView(record));
routingTable.onExternalViewChange(externalViewList, changeContext);
instancesList = routingTable.getInstances("TESTDB", "TESTDB_0", "MASTER");
AssertJUnit.assertNotNull(instancesList);
AssertJUnit.assertEquals(instancesList.size(), 1);
instancesSet = routingTable.getInstances("TESTDB", "MASTER");
AssertJUnit.assertNotNull(instancesSet);
AssertJUnit.assertEquals(instancesSet.size(), 2);
instancesSet = routingTable.getInstances("TESTDB", "SLAVE");
AssertJUnit.assertNotNull(instancesSet);
AssertJUnit.assertEquals(instancesSet.size(), 2);
instancesArray = new InstanceConfig[instancesSet.size()];
instancesSet.toArray(instancesArray);
AssertJUnit.assertEquals(instancesArray[0].getHostName(), "localhost");
AssertJUnit.assertEquals(instancesArray[0].getPort(), "8900");
AssertJUnit.assertEquals(instancesArray[1].getHostName(), "localhost");
AssertJUnit.assertEquals(instancesArray[1].getPort(), "8901");
} finally {
routingTable.shutdown();
}
}
@Test()
public void testMultiThread() throws Exception {
final RoutingTableProvider routingTable = new RoutingTableProvider();
List<ExternalView> externalViewList = new ArrayList<>();
try {
ZNRecord record = new ZNRecord("TESTDB");
for (int i = 0; i < 1000; i++) {
add(record, "TESTDB_" + i, "localhost_8900", "MASTER");
}
externalViewList.add(new ExternalView(record));
routingTable.onExternalViewChange(externalViewList, changeContext);
Callable<Boolean> runnable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
int count = 0;
while (count < 100) {
List<InstanceConfig> instancesList =
routingTable.getInstances("TESTDB", "TESTDB_0", "MASTER");
AssertJUnit.assertEquals(instancesList.size(), 1);
// System.out.println(System.currentTimeMillis() + "-->"
// + instancesList.size());
Thread.sleep(5);
count++;
}
} catch (InterruptedException e) {
// e.printStackTrace();
}
return true;
}
};
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Future<Boolean> submit = executor.submit(runnable);
int count = 0;
while (count < 10) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
routingTable.onExternalViewChange(externalViewList, changeContext);
count++;
}
Boolean result = submit.get(60, TimeUnit.SECONDS);
AssertJUnit.assertEquals(result, Boolean.TRUE);
} finally {
routingTable.shutdown();
}
}
private void add(ZNRecord record, String stateUnitKey, String instanceName, String state) {
Map<String, String> stateUnitKeyMap = record.getMapField(stateUnitKey);
if (stateUnitKeyMap == null) {
stateUnitKeyMap = new HashMap<>();
record.setMapField(stateUnitKey, stateUnitKeyMap);
}
stateUnitKeyMap.put(instanceName, state);
record.setMapField(stateUnitKey, stateUnitKeyMap);
}
}
| 9,425 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestListenerCallbackBatchMode.java
|
package org.apache.helix;
/*
* 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.Random;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.api.listeners.BatchMode;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestListenerCallbackBatchMode extends ZkUnitTestBase {
class Listener implements InstanceConfigChangeListener, IdealStateChangeListener {
int _idealStateChangedCount = 0;
int _instanceConfigChangedCount = 0;
@Override
public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) {
if (changeContext.getType().equals(NotificationContext.Type.CALLBACK)) {
_idealStateChangedCount++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs,
NotificationContext context) {
if (context.getType().equals(NotificationContext.Type.CALLBACK)) {
_instanceConfigChangedCount++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void reset() {
_idealStateChangedCount = 0;
_instanceConfigChangedCount = 0;
}
}
@BatchMode
class BatchedListener extends Listener {
}
class MixedListener extends Listener {
@BatchMode
@Override
public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) {
super.onIdealStateChange(idealState, changeContext);
}
}
@BatchMode (enabled = false)
class BatchDisableddListener extends Listener {
@Override
public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) {
super.onIdealStateChange(idealState, changeContext);
}
}
private HelixManager _manager;
private int _numNode = 8;
private int _numResource = 8;
String clusterName = TestHelper.getTestClassName();
@BeforeClass
public void beforeClass()
throws Exception {
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
_numResource, // resources
4, // partitions per resource
_numNode, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
_manager =
HelixManagerFactory.getZKHelixManager(clusterName, "localhost", InstanceType.SPECTATOR,
ZK_ADDR);
_manager.connect();
}
@AfterClass
public void afterClass()
throws Exception {
_manager.disconnect();
deleteCluster(clusterName);
}
@Test
public void testNonBatchedListener() throws Exception {
String methodName = TestHelper.getTestMethodName();
System.out.println("START " + methodName + " at " + new Date(System.currentTimeMillis()));
final Listener listener = new Listener();
addListeners(listener);
updateConfigs();
verifyNonbatchedListeners(listener);
removeListeners(listener);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
@Test (dependsOnMethods = {"testNonBatchedListener", "testBatchedListener", "testMixedListener"})
public void testEnableBatchedListenerByJavaProperty() throws Exception {
String methodName = TestHelper.getTestMethodName();
System.out.println("START " + methodName + " at " + new Date(System.currentTimeMillis()));
System.setProperty("isAsyncBatchModeEnabled", "true");
Listener listener = new Listener();
addListeners(listener);
updateConfigs();
verifyBatchedListeners(listener);
System.setProperty("isAsyncBatchModeEnabled", "false");
removeListeners(listener);
System.setProperty("helix.callbackhandler.isAsyncBatchModeEnabled", "true");
listener = new Listener();
addListeners(listener);
updateConfigs();
verifyBatchedListeners(listener);
System.setProperty("helix.callbackhandler.isAsyncBatchModeEnabled", "false");
removeListeners(listener);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
@Test (dependsOnMethods = {"testNonBatchedListener", "testBatchedListener", "testMixedListener"})
public void testDisableBatchedListenerByAnnotation() throws Exception {
String methodName = TestHelper.getTestMethodName();
System.out.println("START " + methodName + " at " + new Date(System.currentTimeMillis()));
System.setProperty("isAsyncBatchModeEnabled", "true");
final Listener listener = new BatchDisableddListener();
addListeners(listener);
updateConfigs();
verifyNonbatchedListeners(listener);
System.setProperty("isAsyncBatchModeEnabled", "false");
removeListeners(listener);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testBatchedListener() throws Exception {
String methodName = TestHelper.getTestMethodName();
System.out.println("START " + methodName + " at " + new Date(System.currentTimeMillis()));
final BatchedListener batchListener = new BatchedListener();
addListeners(batchListener);
updateConfigs();
verifyBatchedListeners(batchListener);
removeListeners(batchListener);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testMixedListener() throws Exception {
String methodName = TestHelper.getTestMethodName();
System.out.println("START " + methodName + " at " + new Date(System.currentTimeMillis()));
final MixedListener mixedListener = new MixedListener();
addListeners(mixedListener);
updateConfigs();
Thread.sleep(4000);
boolean result = (mixedListener._instanceConfigChangedCount == _numNode) && (
mixedListener._idealStateChangedCount < _numResource/2);
Assert.assertTrue(result, "instance callbacks: " + mixedListener._instanceConfigChangedCount
+ ", idealstate callbacks " + mixedListener._idealStateChangedCount + "\ninstance count: "
+ _numNode + ", idealstate counts: " + _numResource);
removeListeners(mixedListener);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
private void verifyNonbatchedListeners(final Listener listener) throws Exception {
Boolean result = TestHelper.verify(new TestHelper.Verifier() {
@Override public boolean verify() {
return (listener._instanceConfigChangedCount == _numNode) && (
listener._idealStateChangedCount == _numResource);
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result,
"instance callbacks: " + listener._instanceConfigChangedCount + ", idealstate callbacks "
+ listener._idealStateChangedCount + "\ninstance count: " + _numNode + ", idealstate counts: " + _numResource);
}
private void verifyBatchedListeners(Listener batchListener) throws InterruptedException {
Thread.sleep(3000);
boolean result = (batchListener._instanceConfigChangedCount < _numNode) && (
batchListener._idealStateChangedCount < _numResource);
Assert.assertTrue(result, "instance callbacks: " + batchListener._instanceConfigChangedCount
+ ", idealstate callbacks " + batchListener._idealStateChangedCount + "\ninstance count: "
+ _numNode + ", idealstate counts: " + _numResource);
}
private void addListeners(Listener listener) throws Exception {
_manager.addInstanceConfigChangeListener(listener);
_manager.addIdealStateChangeListener(listener);
}
private void removeListeners(Listener listener) throws Exception {
_manager.removeListener(new PropertyKey.Builder(_manager.getClusterName()).instanceConfigs(),
listener);
_manager
.removeListener(new PropertyKey.Builder(_manager.getClusterName()).idealStates(), listener);
}
private void updateConfigs() throws InterruptedException {
final Random r = new Random(System.currentTimeMillis());
// test change content
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
final List<String> instances = accessor.getChildNames(keyBuilder.instanceConfigs());
for (String instance : instances) {
InstanceConfig value = accessor.getProperty(keyBuilder.instanceConfig(instance));
value._record.setLongField("TimeStamp", System.currentTimeMillis());
accessor.setProperty(keyBuilder.instanceConfig(instance), value);
Thread.sleep(50);
}
final List<String> resources = accessor.getChildNames(keyBuilder.idealStates());
for (String resource : resources) {
IdealState idealState = accessor.getProperty(keyBuilder.idealStates(resource));
idealState.setNumPartitions(r.nextInt(100));
accessor.setProperty(keyBuilder.idealStates(idealState.getId()), idealState);
Thread.sleep(20); // wait zk callback
}
}
}
| 9,426 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestZNRecord.java
|
package org.apache.helix;
/*
* 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.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class TestZNRecord {
@Test
public void testEquals() {
ZNRecord record1 = new ZNRecord("id");
record1.setSimpleField("k1", "v1");
record1.setMapField("m1", new HashMap<String, String>());
record1.getMapField("m1").put("k1", "v1");
record1.setListField("l1", new ArrayList<String>());
record1.getListField("l1").add("v1");
ZNRecord record2 = new ZNRecord("id");
record2.setSimpleField("k1", "v1");
record2.setMapField("m1", new HashMap<String, String>());
record2.getMapField("m1").put("k1", "v1");
record2.setListField("l1", new ArrayList<String>());
record2.getListField("l1").add("v1");
AssertJUnit.assertEquals(record1, record2);
record2.setSimpleField("k2", "v1");
AssertJUnit.assertNotSame(record1, record2);
}
@Test
public void testMerge() {
ZNRecord record = new ZNRecord("record1");
// set simple field
record.setSimpleField("simpleKey1", "simpleValue1");
// set list field
List<String> list1 = new ArrayList<String>();
list1.add("list1Value1");
list1.add("list1Value2");
record.setListField("listKey1", list1);
// set map field
Map<String, String> map1 = new HashMap<String, String>();
map1.put("map1Key1", "map1Value1");
record.setMapField("mapKey1", map1);
// System.out.println(record);
ZNRecord updateRecord = new ZNRecord("updateRecord");
// set simple field
updateRecord.setSimpleField("simpleKey2", "simpleValue2");
// set list field
List<String> newList1 = new ArrayList<String>();
newList1.add("list1Value1");
newList1.add("list1Value2");
newList1.add("list1NewValue1");
newList1.add("list1NewValue2");
updateRecord.setListField("listKey1", newList1);
List<String> list2 = new ArrayList<String>();
list2.add("list2Value1");
list2.add("list2Value2");
updateRecord.setListField("listKey2", list2);
// set map field
Map<String, String> newMap1 = new HashMap<String, String>();
newMap1.put("map1NewKey1", "map1NewValue1");
updateRecord.setMapField("mapKey1", newMap1);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("map2Key1", "map2Value1");
updateRecord.setMapField("mapKey2", map2);
// System.out.println(updateRecord);
record.merge(updateRecord);
// System.out.println(record);
ZNRecord expectRecord = new ZNRecord("record1");
expectRecord.setSimpleField("simpleKey1", "simpleValue1");
expectRecord.setSimpleField("simpleKey2", "simpleValue2");
List<String> expectList1 = new ArrayList<String>();
expectList1.add("list1Value1");
expectList1.add("list1Value2");
expectList1.add("list1Value1");
expectList1.add("list1Value2");
expectList1.add("list1NewValue1");
expectList1.add("list1NewValue2");
expectRecord.setListField("listKey1", expectList1);
List<String> expectList2 = new ArrayList<String>();
expectList2.add("list2Value1");
expectList2.add("list2Value2");
expectRecord.setListField("listKey2", expectList2);
Map<String, String> expectMap1 = new HashMap<String, String>();
expectMap1.put("map1Key1", "map1Value1");
expectMap1.put("map1NewKey1", "map1NewValue1");
expectRecord.setMapField("mapKey1", expectMap1);
Map<String, String> expectMap2 = new HashMap<String, String>();
expectMap2.put("map2Key1", "map2Value1");
expectRecord.setMapField("mapKey2", expectMap2);
Assert.assertEquals(record, expectRecord, "Should be equal.");
}
}
| 9,427 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestListenerCallbackPrefetch.java
|
package org.apache.helix;
/*
* 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.PropertyKey.Builder;
import org.apache.helix.api.listeners.PreFetch;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestListenerCallbackPrefetch extends ZkUnitTestBase {
class PrefetchListener implements InstanceConfigChangeListener, IdealStateChangeListener {
boolean _idealStateChanged = false;
boolean _instanceConfigChanged = false;
boolean _containIdealStates = false;
boolean _containInstanceConfig = false;
@Override
public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) {
_idealStateChanged = true;
_containIdealStates = idealState.isEmpty()? false : true;
}
@Override
public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs, NotificationContext context) {
_instanceConfigChanged = true;
_containInstanceConfig = instanceConfigs.isEmpty()? false : true;
}
public void reset() {
_idealStateChanged = false;
_instanceConfigChanged = false;
_containIdealStates = false;
_containInstanceConfig = false;
}
}
@PreFetch (enabled = false)
class NonPrefetchListener extends PrefetchListener {
}
class MixedPrefetchListener extends PrefetchListener {
@PreFetch(enabled = false)
@Override
public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) {
_idealStateChanged = true;
_containIdealStates = idealState.isEmpty()? false : true;
}
}
private HelixManager _manager;
String clusterName = TestHelper.getTestClassName();
@BeforeClass
public void beforeClass()
throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
int n = 2;
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
_manager =
HelixManagerFactory.getZKHelixManager(clusterName, "localhost", InstanceType.SPECTATOR,
ZK_ADDR);
_manager.connect();
}
@AfterClass
public void afterClass()
throws Exception {
_manager.disconnect();
deleteCluster(clusterName);
}
@Test
public void testPrefetch() throws Exception {
String methodName = TestHelper.getTestMethodName();
System.out.println("START " + methodName + " at " + new Date(System.currentTimeMillis()));
PrefetchListener listener = new PrefetchListener();
_manager.addInstanceConfigChangeListener(listener);
_manager.addIdealStateChangeListener(listener);
Assert.assertTrue(listener._instanceConfigChanged);
Assert.assertTrue(listener._idealStateChanged);
Assert.assertTrue(listener._containInstanceConfig);
Assert.assertTrue(listener._containIdealStates);
listener.reset();
// test change content
updateInstanceConfig();
updateIdealState();
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._instanceConfigChanged);
Assert.assertTrue(listener._containInstanceConfig);
Assert.assertTrue(listener._idealStateChanged);
Assert.assertTrue(listener._containIdealStates);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testNoPrefetch() throws Exception {
String methodName = TestHelper.getTestMethodName();
NonPrefetchListener listener = new NonPrefetchListener();
_manager.addInstanceConfigChangeListener(listener);
_manager.addIdealStateChangeListener(listener);
Assert.assertTrue(listener._instanceConfigChanged);
Assert.assertTrue(listener._idealStateChanged);
Assert.assertFalse(listener._containInstanceConfig);
Assert.assertFalse(listener._containIdealStates);
listener.reset();
updateInstanceConfig();
updateIdealState();
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._instanceConfigChanged);
Assert.assertFalse(listener._containInstanceConfig);
Assert.assertTrue(listener._idealStateChanged);
Assert.assertFalse(listener._containIdealStates);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testMixed() throws Exception {
String methodName = TestHelper.getTestMethodName();
MixedPrefetchListener listener = new MixedPrefetchListener();
_manager.addInstanceConfigChangeListener(listener);
_manager.addIdealStateChangeListener(listener);
Assert.assertTrue(listener._instanceConfigChanged);
Assert.assertTrue(listener._idealStateChanged);
Assert.assertTrue(listener._containInstanceConfig);
Assert.assertFalse(listener._containIdealStates);
listener.reset();
updateInstanceConfig();
updateIdealState();
Thread.sleep(500); // wait zk callback
Assert.assertTrue(listener._instanceConfigChanged);
Assert.assertTrue(listener._containInstanceConfig);
Assert.assertTrue(listener._idealStateChanged);
Assert.assertFalse(listener._containIdealStates);
System.out.println("END " + methodName + " at " + new Date(System.currentTimeMillis()));
}
private void updateInstanceConfig() {
// test change content
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
String instanceName = "localhost_12918";
HelixProperty value = accessor.getProperty(keyBuilder.instanceConfig(instanceName));
value._record.setLongField("TimeStamp", System.currentTimeMillis());
accessor.setProperty(keyBuilder.instanceConfig(instanceName), value);
}
private void updateIdealState() {
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
Builder keyBuilder = accessor.keyBuilder();
List<String> idealStates = accessor.getChildNames(keyBuilder.idealStates());
IdealState idealState = accessor.getProperty(keyBuilder.idealStates(idealStates.get(0)));
idealState.setNumPartitions((int)(System.currentTimeMillis()%50L));
accessor.setProperty(keyBuilder.idealStates(idealState.getId()), idealState);
}
}
| 9,428 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestConfigAccessor.java
|
package org.apache.helix;
/*
* 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.cloud.constants.CloudProvider;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.model.CloudConfig;
import org.apache.helix.model.ConfigScope;
import org.apache.helix.model.HelixConfigScope;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.RESTConfig;
import org.apache.helix.model.builder.ConfigScopeBuilder;
import org.apache.helix.model.builder.HelixConfigScopeBuilder;
import org.apache.helix.tools.ClusterSetup;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestConfigAccessor extends ZkUnitTestBase {
@Test
public void testBasic() 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, "localhost", "TestDB", 1, 10, 5, 3,
"MasterSlave", true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ConfigAccessor configAccessorZkAddr = new ConfigAccessor(ZK_ADDR);
ConfigScope clusterScope = new ConfigScopeBuilder().forCluster(clusterName).build();
// cluster scope config
String clusterConfigValue = configAccessor.get(clusterScope, "clusterConfigKey");
Assert.assertNull(clusterConfigValue);
// also test with ConfigAccessor created with ZkAddr
clusterConfigValue = configAccessorZkAddr.get(clusterScope, "clusterConfigKey");
Assert.assertNull(clusterConfigValue);
configAccessor.set(clusterScope, "clusterConfigKey", "clusterConfigValue");
clusterConfigValue = configAccessor.get(clusterScope, "clusterConfigKey");
Assert.assertEquals(clusterConfigValue, "clusterConfigValue");
configAccessorZkAddr.set(clusterScope, "clusterConfigKey", "clusterConfigValue");
clusterConfigValue = configAccessorZkAddr.get(clusterScope, "clusterConfigKey");
Assert.assertEquals(clusterConfigValue, "clusterConfigValue");
// resource scope config
ConfigScope resourceScope =
new ConfigScopeBuilder().forCluster(clusterName).forResource("testResource").build();
configAccessor.set(resourceScope, "resourceConfigKey", "resourceConfigValue");
String resourceConfigValue = configAccessor.get(resourceScope, "resourceConfigKey");
Assert.assertEquals(resourceConfigValue, "resourceConfigValue");
// partition scope config
ConfigScope partitionScope = new ConfigScopeBuilder().forCluster(clusterName)
.forResource("testResource").forPartition("testPartition").build();
configAccessor.set(partitionScope, "partitionConfigKey", "partitionConfigValue");
String partitionConfigValue = configAccessor.get(partitionScope, "partitionConfigKey");
Assert.assertEquals(partitionConfigValue, "partitionConfigValue");
// participant scope config
ConfigScope participantScope =
new ConfigScopeBuilder().forCluster(clusterName).forParticipant("localhost_12918").build();
configAccessor.set(participantScope, "participantConfigKey", "participantConfigValue");
String participantConfigValue = configAccessor.get(participantScope, "participantConfigKey");
Assert.assertEquals(participantConfigValue, "participantConfigValue");
List<String> keys = configAccessor.getKeys(ConfigScopeProperty.RESOURCE, clusterName);
Assert.assertEquals(keys.size(), 1, "should be [testResource]");
Assert.assertEquals(keys.get(0), "testResource");
keys = configAccessor.getKeys(ConfigScopeProperty.CLUSTER, clusterName);
Assert.assertEquals(keys.size(), 1, "should be [" + clusterName + "]");
Assert.assertEquals(keys.get(0), clusterName);
keys = configAccessor.getKeys(ConfigScopeProperty.PARTICIPANT, clusterName);
Assert.assertEquals(keys.size(), 5, "should be [localhost_12918~22] sorted");
Assert.assertEquals(keys.get(0), "localhost_12918");
Assert.assertEquals(keys.get(4), "localhost_12922");
keys = configAccessor.getKeys(ConfigScopeProperty.PARTITION, clusterName, "testResource");
Assert.assertEquals(keys.size(), 1, "should be [testPartition]");
Assert.assertEquals(keys.get(0), "testPartition");
keys = configAccessor.getKeys(ConfigScopeProperty.RESOURCE, clusterName, "testResource");
Assert.assertEquals(keys.size(), 1, "should be [resourceConfigKey]");
Assert.assertEquals(keys.get(0), "resourceConfigKey");
keys = configAccessor.getKeys(ConfigScopeProperty.CLUSTER, clusterName, clusterName);
Assert.assertEquals(keys.size(), 1, "should be [clusterConfigKey]");
Assert.assertEquals(keys.get(0), "clusterConfigKey");
keys = configAccessor.getKeys(ConfigScopeProperty.PARTICIPANT, clusterName, "localhost_12918");
System.out.println((keys));
Assert.assertEquals(keys.size(), 3, "should be [HELIX_HOST, HELIX_PORT, participantConfigKey]");
Assert.assertEquals(keys.get(2), "participantConfigKey");
keys = configAccessor.getKeys(ConfigScopeProperty.PARTITION, clusterName, "testResource",
"testPartition");
Assert.assertEquals(keys.size(), 1, "should be [partitionConfigKey]");
Assert.assertEquals(keys.get(0), "partitionConfigKey");
// test configAccessor.remove()
configAccessor.remove(clusterScope, "clusterConfigKey");
clusterConfigValue = configAccessor.get(clusterScope, "clusterConfigKey");
Assert.assertNull(clusterConfigValue, "Should be null since it's removed");
configAccessor.remove(resourceScope, "resourceConfigKey");
resourceConfigValue = configAccessor.get(resourceScope, "resourceConfigKey");
Assert.assertNull(resourceConfigValue, "Should be null since it's removed");
configAccessor.remove(partitionScope, "partitionConfigKey");
partitionConfigValue = configAccessor.get(partitionScope, "partitionConfigKey");
Assert.assertNull(partitionConfigValue, "Should be null since it's removed");
configAccessor.remove(participantScope, "participantConfigKey");
participantConfigValue = configAccessor.get(partitionScope, "participantConfigKey");
Assert.assertNull(participantConfigValue, "Should be null since it's removed");
// negative tests
try {
new ConfigScopeBuilder().forPartition("testPartition").build();
Assert.fail("Should fail since cluster name is not set");
} catch (Exception e) {
// OK
}
try {
new ConfigScopeBuilder().forCluster("testCluster").forPartition("testPartition").build();
Assert.fail("Should fail since resource name is not set");
} catch (Exception e) {
// OK
}
try {
new ConfigScopeBuilder().forParticipant("testParticipant").build();
Assert.fail("Should fail since cluster name is not set");
} catch (Exception e) {
// OK
}
TestHelper.dropCluster(clusterName, _gZkClient);
configAccessor.close();
configAccessorZkAddr.close();
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
// HELIX-25: set participant Config should check existence of instance
@Test
public void testSetNonexistentParticipantConfig() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
ZKHelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.addCluster(clusterName, true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ConfigScope participantScope =
new ConfigScopeBuilder().forCluster(clusterName).forParticipant("localhost_12918").build();
try {
configAccessor.set(participantScope, "participantConfigKey", "participantConfigValue");
Assert.fail(
"Except fail to set participant-config because participant: localhost_12918 is not added to cluster yet");
} catch (HelixException e) {
// OK
}
admin.addInstance(clusterName, new InstanceConfig("localhost_12918"));
try {
configAccessor.set(participantScope, "participantConfigKey", "participantConfigValue");
} catch (Exception e) {
Assert.fail(
"Except succeed to set participant-config because participant: localhost_12918 has been added to cluster");
}
String participantConfigValue = configAccessor.get(participantScope, "participantConfigKey");
Assert.assertEquals(participantConfigValue, "participantConfigValue");
admin.dropCluster(clusterName);
configAccessor.close();
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testSetRestConfig() {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
ZKHelixAdmin admin = new ZKHelixAdmin(ZK_ADDR);
admin.addCluster(clusterName, true);
ConfigAccessor configAccessor = new ConfigAccessor(ZK_ADDR);
HelixConfigScope scope =
new HelixConfigScopeBuilder(ConfigScopeProperty.REST).forCluster(clusterName).build();
Assert.assertNull(configAccessor.getRESTConfig(clusterName));
RESTConfig restConfig = new RESTConfig(clusterName);
restConfig.set(RESTConfig.SimpleFields.CUSTOMIZED_HEALTH_URL, "TEST_URL");
configAccessor.setRESTConfig(clusterName, restConfig);
Assert.assertEquals(restConfig, configAccessor.getRESTConfig(clusterName));
}
@Test
public void testUpdateAndDeleteRestConfig() {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
ZKHelixAdmin admin = new ZKHelixAdmin(ZK_ADDR);
admin.addCluster(clusterName, true);
ConfigAccessor configAccessor = new ConfigAccessor(ZK_ADDR);
HelixConfigScope scope =
new HelixConfigScopeBuilder(ConfigScopeProperty.REST).forCluster(clusterName).build();
Assert.assertNull(configAccessor.getRESTConfig(clusterName));
// Update
// No rest config exist
RESTConfig restConfig = new RESTConfig(clusterName);
restConfig.set(RESTConfig.SimpleFields.CUSTOMIZED_HEALTH_URL, "TEST_URL");
configAccessor.updateRESTConfig(clusterName, restConfig);
Assert.assertEquals(restConfig, configAccessor.getRESTConfig(clusterName));
// Rest config exists
restConfig.set(RESTConfig.SimpleFields.CUSTOMIZED_HEALTH_URL, "TEST_URL_2");
configAccessor.updateRESTConfig(clusterName, restConfig);
Assert.assertEquals(restConfig, configAccessor.getRESTConfig(clusterName));
// Delete
// Existing rest config
configAccessor.deleteRESTConfig(clusterName);
Assert.assertNull(configAccessor.getRESTConfig(clusterName));
// Nonexisting rest config
admin.addCluster(clusterName, true);
try {
configAccessor.deleteRESTConfig(clusterName);
Assert.fail("Helix exception expected.");
} catch (HelixException e) {
Assert.assertEquals(e.getMessage(),
"Fail to delete REST config. cluster: " + clusterName + " does not have a rest config.");
}
// Nonexisting cluster
String anotherClusterName = "anotherCluster";
try {
configAccessor.deleteRESTConfig(anotherClusterName);
Assert.fail("Helix exception expected.");
} catch (HelixException e) {
Assert.assertEquals(e.getMessage(),
"Fail to delete REST config. cluster: " + anotherClusterName + " is NOT setup.");
}
}
public void testUpdateCloudConfig() throws Exception {
ClusterSetup _clusterSetup = new ClusterSetup(ZK_ADDR);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder();
cloudConfigInitBuilder.setCloudEnabled(true);
cloudConfigInitBuilder.setCloudID("TestCloudID");
List<String> sourceList = new ArrayList<String>();
sourceList.add("TestURL");
cloudConfigInitBuilder.setCloudInfoSources(sourceList);
cloudConfigInitBuilder.setCloudInfoProcessorName("TestProcessor");
cloudConfigInitBuilder.setCloudProvider(CloudProvider.CUSTOMIZED);
CloudConfig cloudConfigInit = cloudConfigInitBuilder.build();
_clusterSetup.addCluster(clusterName, false, cloudConfigInit);
// Read CloudConfig from Zookeeper and check the content
ConfigAccessor _configAccessor = new ConfigAccessor(ZK_ADDR);
CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertTrue(cloudConfigFromZk.isCloudEnabled());
Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestCloudID");
List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources();
Assert.assertEquals(listUrlFromZk.get(0), "TestURL");
Assert.assertEquals(cloudConfigFromZk.getCloudInfoProcessorName(), "TestProcessor");
Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.CUSTOMIZED.name());
// Change the processor name and check if processor name has been changed in Zookeeper.
CloudConfig.Builder cloudConfigToUpdateBuilder = new CloudConfig.Builder();
cloudConfigToUpdateBuilder.setCloudInfoProcessorName("TestProcessor2");
CloudConfig cloudConfigToUpdate = cloudConfigToUpdateBuilder.build();
_configAccessor.updateCloudConfig(clusterName, cloudConfigToUpdate);
cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertTrue(cloudConfigFromZk.isCloudEnabled());
Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestCloudID");
listUrlFromZk = cloudConfigFromZk.getCloudInfoSources();
Assert.assertEquals(listUrlFromZk.get(0), "TestURL");
Assert.assertEquals(cloudConfigFromZk.getCloudInfoProcessorName(), "TestProcessor2");
Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.CUSTOMIZED.name());
}
@Test
public void testDeleteCloudConfig() throws Exception {
ClusterSetup _clusterSetup = new ClusterSetup(ZK_ADDR);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder();
cloudConfigInitBuilder.setCloudEnabled(true);
cloudConfigInitBuilder.setCloudID("TestCloudID");
List<String> sourceList = new ArrayList<String>();
sourceList.add("TestURL");
cloudConfigInitBuilder.setCloudInfoSources(sourceList);
cloudConfigInitBuilder.setCloudInfoProcessorName("TestProcessor");
cloudConfigInitBuilder.setCloudProvider(CloudProvider.AZURE);
CloudConfig cloudConfigInit = cloudConfigInitBuilder.build();
_clusterSetup.addCluster(clusterName, false, cloudConfigInit);
// Read CloudConfig from Zookeeper and check the content
ConfigAccessor _configAccessor = new ConfigAccessor(ZK_ADDR);
CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertTrue(cloudConfigFromZk.isCloudEnabled());
Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestCloudID");
List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources();
Assert.assertEquals(listUrlFromZk.get(0), "TestURL");
Assert.assertEquals(cloudConfigFromZk.getCloudInfoProcessorName(), "TestProcessor");
Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.AZURE.name());
// Change the processor name and check if processor name has been changed in Zookeeper.
CloudConfig.Builder cloudConfigBuilderToDelete = new CloudConfig.Builder();
cloudConfigBuilderToDelete.setCloudInfoProcessorName("TestProcessor");
cloudConfigBuilderToDelete.setCloudID("TestCloudID");
CloudConfig cloudConfigToDelete = cloudConfigBuilderToDelete.build();
_configAccessor.deleteCloudConfigFields(clusterName, cloudConfigToDelete);
cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertTrue(cloudConfigFromZk.isCloudEnabled());
Assert.assertNull(cloudConfigFromZk.getCloudID());
listUrlFromZk = cloudConfigFromZk.getCloudInfoSources();
Assert.assertEquals(listUrlFromZk.get(0), "TestURL");
Assert.assertNull(cloudConfigFromZk.getCloudInfoProcessorName());
Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.AZURE.name());
}
}
| 9,429 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestRelayIdealStateCalculator.java
|
package org.apache.helix;
/*
* 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.model.IdealState;
import org.apache.helix.tools.IdealStateCalculatorForEspressoRelay;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestRelayIdealStateCalculator {
@Test()
public void testEspressoStorageClusterIdealState() throws Exception {
testEspressoStorageClusterIdealState(15, 9, 3);
testEspressoStorageClusterIdealState(15, 6, 3);
testEspressoStorageClusterIdealState(15, 6, 2);
testEspressoStorageClusterIdealState(6, 4, 2);
}
public void testEspressoStorageClusterIdealState(int partitions, int nodes, int replica)
throws Exception {
List<String> storageNodes = new ArrayList<String>();
for (int i = 0; i < partitions; i++) {
storageNodes.add("localhost:123" + i);
}
List<String> relays = new ArrayList<String>();
for (int i = 0; i < nodes; i++) {
relays.add("relay:123" + i);
}
IdealState idealstate =
IdealStateCalculatorForEspressoRelay.calculateRelayIdealState(storageNodes, relays, "TEST",
replica, "Leader", "Standby", "LeaderStandby");
Assert.assertEquals(idealstate.getRecord().getListFields().size(), idealstate.getRecord()
.getMapFields().size());
Map<String, Integer> countMap = new TreeMap<String, Integer>();
for (String key : idealstate.getRecord().getListFields().keySet()) {
Assert.assertEquals(idealstate.getRecord().getListFields().get(key).size(), idealstate
.getRecord().getMapFields().get(key).size());
List<String> list = idealstate.getRecord().getListFields().get(key);
Map<String, String> map = idealstate.getRecord().getMapFields().get(key);
Assert.assertEquals(list.size(), replica);
for (String val : list) {
if (!countMap.containsKey(val)) {
countMap.put(val, 1);
} else {
countMap.put(val, countMap.get(val) + 1);
}
Assert.assertTrue(map.containsKey(val));
}
}
for (String nodeName : countMap.keySet()) {
Assert.assertTrue(countMap.get(nodeName) <= partitions * replica / nodes + 1);
// System.out.println(nodeName + " " + countMap.get(nodeName));
}
System.out.println();
}
}
| 9,430 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/TestGetProperty.java
|
package org.apache.helix;
/*
* 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.io.InputStream;
import java.util.Properties;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestGetProperty {
@Test
public void testGetProperty() {
String version;
Properties props = new Properties();
try {
InputStream stream =
Thread.currentThread().getContextClassLoader()
.getResourceAsStream("cluster-manager-version.properties");
props.load(stream);
version = props.getProperty("clustermanager.version");
Assert.assertNotNull(version);
System.out.println("cluster-manager-version:" + version);
} catch (IOException e) {
// e.printStackTrace();
Assert.fail("could not open cluster-manager-version.properties. ", e);
}
}
}
| 9,431 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/tools/TestHelixAdminCli.java
|
package org.apache.helix.tools;
/*
* 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.FileWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterDistributedController;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZKUtil;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.store.ZNRecordJsonSerializer;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterStateVerifier.MasterNbInExtViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class TestHelixAdminCli extends ZkTestBase {
private static final long SLEEP_DURATION = 1000L;
private String clusterName = TestHelper.getTestClassName();
private String grandClusterName = clusterName + "_grand";
@AfterMethod
public void endTest(Method testMethod, ITestContext testContext) {
try {
deleteCluster(clusterName);
deleteCluster(grandClusterName);
} catch (Exception ignored) {
// OK
}
}
@Test
public void testAddCluster() throws Exception {
String command = "--zkSvr localhost:2183 -addCluster clusterTest";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// malformed cluster name
command = "--zkSvr localhost:2183 -addCluster /ClusterTest";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("ClusterSetup should fail since /ClusterTest is not a valid name");
} catch (Exception e) {
// OK
}
// Add the grand cluster
// " is ignored by zk
command = "--zkSvr localhost:2183 -addCluster \"Klazt3rz";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "--zkSvr localhost:2183 -addCluster \\ClusterTest";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// Add already exist cluster
command = "--zkSvr localhost:2183 -addCluster clusterTest";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// make sure clusters are properly setup
Assert.assertTrue(ZKUtil.isClusterSetup("Klazt3rz", _gZkClient));
Assert.assertTrue(ZKUtil.isClusterSetup("clusterTest", _gZkClient));
Assert.assertTrue(ZKUtil.isClusterSetup("\\ClusterTest", _gZkClient));
// delete cluster without resource and instance
command = "-zkSvr localhost:2183 -dropCluster \"Klazt3rz";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -dropCluster \\ClusterTest";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -dropCluster clusterTest1";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -dropCluster clusterTest";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertFalse(_gZkClient.exists("/Klazt3rz"));
Assert.assertFalse(_gZkClient.exists("/clusterTest"));
Assert.assertFalse(_gZkClient.exists("/\\ClusterTest"));
Assert.assertFalse(_gZkClient.exists("/clusterTest1"));
}
@Test(dependsOnMethods = "testAddCluster")
public void testAddResource() throws Exception {
String command = "-zkSvr localhost:2183 -addCluster " + clusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -addResource " + clusterName + " db_22 144 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -addResource " + clusterName + " db_11 44 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// Add duplicate resource
command = "-zkSvr localhost:2183 -addResource " + clusterName + " db_22 55 OnlineOffline";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("ClusterSetup should fail since resource db_22 already exists");
} catch (Exception e) {
// OK
}
// drop resource now
command = "-zkSvr localhost:2183 -dropResource " + clusterName + " db_11 ";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
@Test(dependsOnMethods = "testAddResource")
public void testAddInstance() throws Exception {
String command = "-zkSvr localhost:2183 -addCluster " + clusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
for (int i = 0; i < 3; i++) {
command = "-zkSvr localhost:2183 -addNode " + clusterName + " localhost:123" + i;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
command = "-zkSvr localhost:2183 -addNode " + clusterName
+ " localhost:1233;localhost:1234;localhost:1235;localhost:1236";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// delete enabled node
command = "-zkSvr localhost:2183 -dropNode " + clusterName + " localhost:1236";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("delete node localhost:1236 should fail since it's not disabled");
} catch (Exception e) {
// OK
}
// delete non-exist node
command = "-zkSvr localhost:2183 -dropNode " + clusterName + " localhost:12367";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("delete node localhost:1237 should fail since it doesn't exist");
} catch (Exception e) {
// OK
}
// disable node
command = "-zkSvr localhost:2183 -enableInstance " + clusterName + " localhost:1236 false";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -dropNode " + clusterName + " localhost:1236";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// add a duplicated host
command = "-zkSvr localhost:2183 -addNode " + clusterName + " localhost:1234";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("add node localhost:1234 should fail since it already exists");
} catch (Exception e) {
// OK
}
}
@Test(dependsOnMethods = "testAddInstance")
public void testRebalanceResource() throws Exception {
String command = "-zkSvr localhost:2183 -addCluster " + clusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -addResource " + clusterName + " db_11 12 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
for (int i = 0; i < 6; i++) {
command = "-zkSvr localhost:2183 -addNode " + clusterName + " localhost:123" + i;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
command = "-zkSvr localhost:2183 -rebalance " + clusterName + " db_11 3";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -dropResource " + clusterName + " db_11 ";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// re-add and rebalance
command = "-zkSvr localhost:2183 -addResource " + clusterName + " db_11 48 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -rebalance " + clusterName + " db_11 3";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// rebalance with key prefix
command = "-zkSvr localhost:2183 -rebalance " + clusterName + " db_11 2 -key alias";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
@Test(dependsOnMethods = "testRebalanceResource")
public void testStartCluster() throws Exception {
final int n = 6;
MockParticipantManager[] participants = new MockParticipantManager[n];
ClusterDistributedController[] controllers = new ClusterDistributedController[2];
setupCluster(clusterName, grandClusterName, n, participants, controllers);
// activate clusters
// wrong grand clusterName
String command =
"-zkSvr localhost:2183 -activateCluster " + clusterName + " nonExistGrandCluster true";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail(
"add " + clusterName + " to grandCluster should fail since grandCluster doesn't exists");
} catch (Exception e) {
// OK
}
// wrong cluster name
command =
"-zkSvr localhost:2183 -activateCluster nonExistCluster " + grandClusterName + " true";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("add nonExistCluster to " + grandClusterName
+ " should fail since nonExistCluster doesn't exists");
} catch (Exception e) {
// OK
}
activateCluster();
// drop a running cluster
command = "-zkSvr localhost:2183 -dropCluster " + clusterName;
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("drop " + clusterName + " should fail since it's still running");
} catch (Exception e) {
// OK
}
// verify leader node
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(grandClusterName, baseAccessor);
LiveInstance controllerLeader = accessor.getProperty(accessor.keyBuilder().controllerLeader());
Assert.assertNotNull(controllerLeader,
"controllerLeader should be either controller_9000 or controller_9001");
Assert.assertTrue(controllerLeader.getInstanceName().startsWith("controller_900"));
accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
LiveInstance leader = accessor.getProperty(accessor.keyBuilder().controllerLeader());
for (int i = 0; i < 20; i++) {
if (leader != null) {
break;
}
Thread.sleep(200);
leader = accessor.getProperty(accessor.keyBuilder().controllerLeader());
}
Assert.assertNotNull(leader);
Assert.assertTrue(leader.getInstanceName().startsWith("controller_900"));
boolean verifyResult = ClusterStateVerifier
.verifyByZkCallback(new MasterNbInExtViewVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(verifyResult);
verifyResult = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(verifyResult);
// clean up
for (ClusterDistributedController controller : controllers) {
controller.syncStop();
}
for (ClusterDistributedController controller : controllers) {
if (controller.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
for (MockParticipantManager participant : participants) {
if (participant.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
}
@Test(dependsOnMethods = "testStartCluster")
public void testDropAddResource() throws Exception {
final int n = 6;
MockParticipantManager[] participants = new MockParticipantManager[n];
ClusterDistributedController[] controllers = new ClusterDistributedController[2];
setupCluster(clusterName, grandClusterName, n, participants, controllers);
activateCluster();
// save ideal state
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
IdealState idealState = accessor.getProperty(accessor.keyBuilder().idealStates("db_11"));
ZNRecordJsonSerializer serializer = new ZNRecordJsonSerializer();
String tmpDir = System.getProperty("java.io.tmpdir");
if (tmpDir == null) {
tmpDir = "/tmp";
}
final String tmpIdealStateFile = tmpDir + "/" + clusterName + "_idealState.log";
FileWriter fos = new FileWriter(tmpIdealStateFile);
PrintWriter pw = new PrintWriter(fos);
pw.write(new String(serializer.serialize(idealState.getRecord())));
pw.close();
String command = "-zkSvr " + ZK_ADDR + " -dropResource " + clusterName + " db_11 ";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
boolean verifyResult = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(verifyResult);
command =
"-zkSvr " + ZK_ADDR + " -addIdealState " + clusterName + " db_11 " + tmpIdealStateFile;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
verifyResult = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(verifyResult);
IdealState idealState2 = accessor.getProperty(accessor.keyBuilder().idealStates("db_11"));
Assert.assertEquals(idealState.getRecord(), idealState2.getRecord());
// clean up
for (ClusterDistributedController controller : controllers) {
controller.syncStop();
}
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
}
private void setupCluster(String clusterName, String grandClusterName, final int n,
MockParticipantManager[] participants, ClusterDistributedController[] controllers)
throws Exception {
// add cluster
String command = "-zkSvr " + ZK_ADDR + " -addCluster " + clusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// add grand cluster
command = "-zkSvr " + ZK_ADDR + " -addCluster " + grandClusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// add nodes
for (int i = 0; i < n; i++) {
command = "-zkSvr " + ZK_ADDR + " -addNode " + clusterName + " localhost:123" + i;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
// add resource
command = "-zkSvr " + ZK_ADDR + " -addResource " + clusterName + " db_11 48 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// rebalance with key prefix
command = "-zkSvr " + ZK_ADDR + " -rebalance " + clusterName + " db_11 2 -key alias";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// add nodes to grand cluster
command =
"-zkSvr " + ZK_ADDR + " -addNode " + grandClusterName + " controller:9000;controller:9001";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// start mock nodes
for (int i = 0; i < n; i++) {
String instanceName = "localhost_123" + i;
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// start controller nodes
for (int i = 0; i < 2; i++) {
controllers[i] =
new ClusterDistributedController(ZK_ADDR, grandClusterName, "controller_900" + i);
controllers[i].syncStart();
}
Thread.sleep(SLEEP_DURATION);
}
@Test(dependsOnMethods = "testDropAddResource")
public void testInstanceOperations() throws Exception {
final int n = 6;
MockParticipantManager[] participants = new MockParticipantManager[n];
ClusterDistributedController[] controllers = new ClusterDistributedController[2];
setupCluster(clusterName, grandClusterName, n, participants, controllers);
activateCluster();
// drop node should fail if the node is not disabled
String command = "-zkSvr " + ZK_ADDR + " -dropNode " + clusterName + " localhost:1232";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("dropNode should fail since the node is not disabled");
} catch (Exception e) {
// OK
}
// disabled node
command = "-zkSvr " + ZK_ADDR + " -enableInstance " + clusterName + " localhost:1232 false";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// Cannot dropNode if the node is not disconnected
command = "-zkSvr " + ZK_ADDR + " -dropNode " + clusterName + " localhost:1232";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("dropNode should fail since the node is not disconnected");
} catch (Exception e) {
// OK
}
// Cannot swapNode if the node is not disconnected
command =
"-zkSvr " + ZK_ADDR + " -swapInstance " + clusterName + " localhost_1232 localhost_12320";
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("swapInstance should fail since the node is not disconnected");
} catch (Exception e) {
// OK
}
// disconnect localhost_1232
participants[2].syncStop();
// add new node then swap instance
command = "-zkSvr " + ZK_ADDR + " -addNode " + clusterName + " localhost:12320";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// swap instance. The instance get swapped out should not exist anymore
command =
"-zkSvr " + ZK_ADDR + " -swapInstance " + clusterName + " localhost_1232 localhost_12320";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
String path = accessor.keyBuilder().instanceConfig("localhost_1232").getPath();
Assert.assertFalse(_gZkClient.exists(path),
path + " should not exist since localhost_1232 has been swapped by localhost_12320");
// clean up
for (ClusterDistributedController controller : controllers) {
controller.syncStop();
}
for (ClusterDistributedController controller : controllers) {
if (controller.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
for (MockParticipantManager participant : participants) {
if (participant.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
}
@Test(dependsOnMethods = "testInstanceOperations")
public void testExpandCluster() throws Exception {
final int n = 6;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
ClusterDistributedController[] controllers = new ClusterDistributedController[2];
setupCluster(clusterName, grandClusterName, n, participants, controllers);
activateCluster();
String command = "-zkSvr " + ZK_ADDR + " -addNode " + clusterName
+ " localhost:12331;localhost:12341;localhost:12351;localhost:12361";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -expandCluster " + clusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
MockParticipantManager[] newParticipants = new MockParticipantManager[4];
for (int i = 3; i <= 6; i++) {
String instanceName = "localhost_123" + i + "1";
newParticipants[i - 3] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
newParticipants[i - 3].syncStart();
}
boolean verifyResult = ClusterStateVerifier
.verifyByZkCallback(new MasterNbInExtViewVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(verifyResult);
verifyResult = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(verifyResult);
// clean up
for (ClusterDistributedController controller : controllers) {
controller.syncStop();
}
for (ClusterDistributedController controller : controllers) {
if (controller.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
for (MockParticipantManager participant : participants) {
if (participant.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
for (MockParticipantManager newParticipant : newParticipants) {
newParticipant.syncStop();
}
for (MockParticipantManager newParticipant : newParticipants) {
if (newParticipant.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
}
@Test(dependsOnMethods = "testExpandCluster")
public void testDeactivateCluster() throws Exception {
final int n = 6;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
ClusterDistributedController[] controllers = new ClusterDistributedController[2];
setupCluster(clusterName, grandClusterName, n, participants, controllers);
activateCluster();
// wait till grand_cluster converge
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(grandClusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME).build();
boolean result = verifier.verifyByPolling();
Assert.assertTrue(result, "grand cluster not converging.");
// deactivate cluster
String command =
"-zkSvr " + ZK_ADDR + " -activateCluster " + clusterName + " " + grandClusterName
+ " false";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
final String path = accessor.keyBuilder().controllerLeader().getPath();
TestHelper.verify(() -> !_gZkClient.exists(path), 10000L);
Assert.assertFalse(_gZkClient.exists(path),
"leader should be gone after deactivate the cluster");
command = "-zkSvr " + ZK_ADDR + " -dropCluster " + clusterName;
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("dropCluster should fail since there are still instances running");
} catch (Exception e) {
// OK
}
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
for (MockParticipantManager participant : participants) {
if (participant.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
command = "-zkSvr localhost:2183 -dropCluster " + clusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s"));
boolean leaderNotExists = TestHelper.verify(() -> {
boolean isLeaderExists = _gZkClient.exists(path);
return isLeaderExists == false;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(leaderNotExists, " mysterious leader out!");
for (ClusterDistributedController controller : controllers) {
controller.syncStop();
}
for (ClusterDistributedController controller : controllers) {
if (controller.isConnected()) {
Thread.sleep(SLEEP_DURATION);
}
}
command = "-zkSvr localhost:2183 -dropCluster " + grandClusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
@Test(dependsOnMethods = "testDeactivateCluster")
public void testInstanceGroupTags() throws Exception {
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
String command = "-zkSvr " + ZK_ADDR + " -addCluster " + clusterName;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "-zkSvr localhost:2183 -addResource " + clusterName + " db_11 12 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
for (int i = 0; i < 6; i++) {
command = "-zkSvr " + ZK_ADDR + " -addNode " + clusterName + " localhost:123" + i;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
for (int i = 0; i < 2; i++) {
command =
"-zkSvr " + ZK_ADDR + " -addInstanceTag " + clusterName + " localhost_123" + i + " tag1";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
for (int i = 2; i < 6; i++) {
command =
"-zkSvr " + ZK_ADDR + " -addInstanceTag " + clusterName + " localhost_123" + i + " tag2";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
command =
"-zkSvr " + ZK_ADDR + " -rebalance " + clusterName + " db_11 2 -instanceGroupTag tag1";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
IdealState dbIs = accessor.getProperty(accessor.keyBuilder().idealStates("db_11"));
Set<String> hosts = new HashSet<>();
for (String p : dbIs.getPartitionSet()) {
for (String hostName : dbIs.getInstanceStateMap(p).keySet()) {
InstanceConfig config =
accessor.getProperty(accessor.keyBuilder().instanceConfig(hostName));
Assert.assertTrue(config.containsTag("tag1"));
hosts.add(hostName);
}
}
Assert.assertEquals(hosts.size(), 2);
command = "-zkSvr " + ZK_ADDR + " -dropResource " + clusterName + " db_11 ";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// re-add and rebalance
command = "-zkSvr " + ZK_ADDR + " -addResource " + clusterName + " db_11 48 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command =
"-zkSvr " + ZK_ADDR + " -rebalance " + clusterName + " db_11 3 -instanceGroupTag tag2";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
dbIs = accessor.getProperty(accessor.keyBuilder().idealStates("db_11"));
hosts = new HashSet<>();
for (String p : dbIs.getPartitionSet()) {
for (String hostName : dbIs.getInstanceStateMap(p).keySet()) {
InstanceConfig config =
accessor.getProperty(accessor.keyBuilder().instanceConfig(hostName));
Assert.assertTrue(config.containsTag("tag2"));
hosts.add(hostName);
}
}
Assert.assertEquals(hosts.size(), 4);
command = "-zkSvr " + ZK_ADDR + " -dropResource " + clusterName + " db_11 ";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
for (int i = 3; i <= 3; i++) {
command = "-zkSvr " + ZK_ADDR + " -removeInstanceTag " + clusterName + " localhost_123" + i
+ " tag2";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
// re-add and rebalance
command = "-zkSvr " + ZK_ADDR + " -addResource " + clusterName + " db_11 48 MasterSlave";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command =
"-zkSvr " + ZK_ADDR + " -rebalance " + clusterName + " db_11 3 -instanceGroupTag tag2";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
dbIs = accessor.getProperty(accessor.keyBuilder().idealStates("db_11"));
hosts = new HashSet<>();
for (String p : dbIs.getPartitionSet()) {
for (String hostName : dbIs.getInstanceStateMap(p).keySet()) {
InstanceConfig config =
accessor.getProperty(accessor.keyBuilder().instanceConfig(hostName));
Assert.assertTrue(config.containsTag("tag2"));
hosts.add(hostName);
}
}
Assert.assertEquals(hosts.size(), 3);
// rebalance with key prefix
command = "-zkSvr " + ZK_ADDR + " -rebalance " + clusterName + " db_11 2 -key alias";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
}
private void activateCluster() throws Exception {
String command =
"-zkSvr localhost:2183 -activateCluster " + clusterName + " " + grandClusterName + " true";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
HelixAdmin admin = _gSetupTool.getClusterManagementTool();
TestHelper.verify(() -> {
if (admin.getResourceExternalView(grandClusterName, clusterName) == null) {
return false;
}
return true;
}, TestHelper.WAIT_DURATION);
}
}
| 9,432 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/tools/TestZkCopy.java
|
package org.apache.helix.tools;
/*
* 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.InstanceType;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.manager.zk.ZKUtil;
import org.apache.helix.tools.commandtools.ZkCopy;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestZkCopy extends ZkUnitTestBase {
@Test
public void test() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
String fromPath = "/" + clusterName + "/from";
_gZkClient.createPersistent(fromPath, true);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
String path = String.format("%s/%d/%d", fromPath, i, j);
_gZkClient.createPersistent(path, true);
_gZkClient.writeData(path, new ZNRecord(String.format("%d/%d", i, j)));
}
}
// Copy
String toPath = "/" + clusterName + "/to";
ZkCopy.main(
new String[] { "--src", "zk://" + ZK_ADDR + fromPath, "--dst", "zk://" + ZK_ADDR + toPath });
// Verify
Assert.assertTrue(_gZkClient.exists(toPath));
Assert.assertNull(_gZkClient.readData(toPath));
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
String path = String.format("%s/%d/%d", toPath, i, j);
Assert.assertTrue(_gZkClient.exists(path));
ZNRecord record = _gZkClient.readData(path);
Assert.assertEquals(String.format("%d/%d", i, j), record.getId());
}
}
_gZkClient.deleteRecursively("/" + clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testSkipCopyExistZnode() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String testName = className + "_" + methodName;
System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis()));
String srcClusterName = testName + "_src";
String dstClusterName = testName + "_dst";
int n = 5;
TestHelper.setupCluster(srcClusterName, 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
TestHelper.setupEmptyCluster(_gZkClient, dstClusterName);
String fromPath = String.format("/%s/INSTANCES", srcClusterName);
String toPath = String.format("/%s/INSTANCES", dstClusterName);
ZkCopy.main(new String[] {
"--src", "zk://" + ZK_ADDR + fromPath, "--dst", "zk://" + ZK_ADDR + toPath
});
fromPath = String.format("/%s/CONFIGS/PARTICIPANT", srcClusterName);
toPath = String.format("/%s/CONFIGS/PARTICIPANT", dstClusterName);
ZkCopy.main(new String[] {
"--src", "zk://" + ZK_ADDR + fromPath, "--dst", "zk://" + ZK_ADDR + toPath
});
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
boolean ret =
ZKUtil
.isInstanceSetup(_gZkClient, dstClusterName, instanceName, InstanceType.PARTICIPANT);
Assert.assertTrue(ret);
}
TestHelper.dropCluster(srcClusterName, _gZkClient);
TestHelper.dropCluster(dstClusterName, _gZkClient);
System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,433 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/tools/TestClusterVerifier.java
|
package org.apache.helix.tools;
/*
* 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 com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.mock.participant.SleepTransition;
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.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier;
import org.apache.helix.tools.ClusterVerifiers.StrictMatchExternalViewVerifier;
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 TestClusterVerifier extends ZkUnitTestBase {
final String[] RESOURCES = {
"resource_semi_MasterSlave", "resource_semi_OnlineOffline",
"resource_full_MasterSlave", "resource_full_OnlineOffline"
};
final String[] SEMI_AUTO_RESOURCES = {RESOURCES[0], RESOURCES[1]};
final String[] FULL_AUTO_RESOURCES = {RESOURCES[2], RESOURCES[3]};
private HelixAdmin _admin;
private MockParticipantManager[] _participants;
private ClusterControllerManager _controller;
private String _clusterName;
private ClusterSetup _setupTool;
@BeforeMethod
public void beforeMethod() throws InterruptedException {
final int NUM_PARTITIONS = 10;
final int NUM_REPLICAS = 3;
// Cluster and resource setup
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
_clusterName = className + "_" + methodName;
_setupTool = new ClusterSetup(ZK_ADDR);
_admin = _setupTool.getClusterManagementTool();
_setupTool.addCluster(_clusterName, true);
_setupTool.addResourceToCluster(_clusterName, RESOURCES[0], NUM_PARTITIONS,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.SEMI_AUTO.toString());
_setupTool.addResourceToCluster(_clusterName, RESOURCES[1], NUM_PARTITIONS,
BuiltInStateModelDefinitions.OnlineOffline.name(), RebalanceMode.SEMI_AUTO.toString());
_setupTool.addResourceToCluster(_clusterName, RESOURCES[2], NUM_PARTITIONS,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO.toString(),
CrushEdRebalanceStrategy.class.getName());
_setupTool.addResourceToCluster(_clusterName, RESOURCES[3], NUM_PARTITIONS,
BuiltInStateModelDefinitions.OnlineOffline.name(), RebalanceMode.FULL_AUTO.toString(),
CrushEdRebalanceStrategy.class.getName());
// Enable persist best possible assignment
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(_clusterName);
clusterConfig.setPersistBestPossibleAssignment(true);
configAccessor.setClusterConfig(_clusterName, clusterConfig);
// Configure and start the participants
_participants = new MockParticipantManager[RESOURCES.length];
for (int i = 0; i < _participants.length; i++) {
String host = "localhost";
int port = 12918 + i;
String id = host + '_' + port;
_setupTool.addInstanceToCluster(_clusterName, id);
_participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, id);
_participants[i].syncStart();
}
// Rebalance the resources
for (int i = 0; i < RESOURCES.length; i++) {
_setupTool.rebalanceResource(_clusterName, RESOURCES[i], NUM_REPLICAS);
}
// Start the controller
_controller = new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
_controller.syncStart();
Thread.sleep(1000);
}
@AfterMethod
public void afterMethod() {
// Cleanup
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
_admin.dropCluster(_clusterName);
}
@Test
public void testDisablePartitionAndStopInstance() throws Exception {
// Just ensure that the entire cluster passes
// ensure that the external view coalesces
HelixClusterVerifier bestPossibleVerifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(bestPossibleVerifier.verify(10000));
// Disable partition for 1 instance, then Full-Auto ExternalView should match IdealState.
_admin.enablePartition(false, _clusterName, _participants[0].getInstanceName(),
FULL_AUTO_RESOURCES[0], Lists.newArrayList(FULL_AUTO_RESOURCES[0] + "_0"));
Assert.assertTrue(bestPossibleVerifier.verify(3000));
// Enable the partition back
_admin.enablePartition(true, _clusterName, _participants[0].getInstanceName(),
FULL_AUTO_RESOURCES[0], Lists.newArrayList(FULL_AUTO_RESOURCES[0] + "_0"));
Assert.assertTrue(bestPossibleVerifier.verify(10000));
// Make 1 instance non-live
_participants[0].syncStop();
Assert.assertTrue(bestPossibleVerifier.verify(10000));
// Recover the participant before next test
String id = _participants[0].getInstanceName();
_participants[0] = new MockParticipantManager(ZK_ADDR, _clusterName, id);
_participants[0].syncStart();
HelixClusterVerifier strictMatchVerifier =
new StrictMatchExternalViewVerifier.Builder(_clusterName)
.setResources(Sets.newHashSet(RESOURCES)).setZkClient(_gZkClient)
.setDeactivatedNodeAwareness(true)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(strictMatchVerifier.verify(10000));
// Disable partition for 1 instance, then Full-Auto ExternalView should match IdealState.
_admin.enablePartition(false, _clusterName, _participants[0].getInstanceName(),
FULL_AUTO_RESOURCES[0], Lists.newArrayList(FULL_AUTO_RESOURCES[0] + "_0"));
Assert.assertTrue(strictMatchVerifier.verify(3000));
// Enable the partition back
_admin.enablePartition(true, _clusterName, _participants[0].getInstanceName(),
FULL_AUTO_RESOURCES[0], Lists.newArrayList(FULL_AUTO_RESOURCES[0] + "_0"));
Assert.assertTrue(strictMatchVerifier.verify(10000));
// Make 1 instance non-live
_participants[0].syncStop();
// Semi-Auto ExternalView matching
for (String resource : SEMI_AUTO_RESOURCES) {
System.out.println("Verify resource: " + resource);
strictMatchVerifier =
new StrictMatchExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setResources(Sets.newHashSet(resource)).setDeactivatedNodeAwareness(true)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(strictMatchVerifier.verify(3000));
}
// Full-Auto ExternalView matching
strictMatchVerifier =
new StrictMatchExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setResources(Sets.newHashSet(FULL_AUTO_RESOURCES)).setDeactivatedNodeAwareness(true)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(strictMatchVerifier.verify(10000));
}
@Test
public void testResourceSubset() throws InterruptedException {
String testDB = "resource-testDB";
_setupTool.addResourceToCluster(_clusterName, testDB, 1,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.SEMI_AUTO.toString());
IdealState idealState = _admin.getResourceIdealState(_clusterName, testDB);
idealState.setReplicas(Integer.toString(2));
idealState.getRecord().setListField(testDB + "_0",
Arrays.asList(_participants[1].getInstanceName(), _participants[2].getInstanceName()));
_admin.setResourceIdealState(_clusterName, testDB, idealState);
// Ensure that this passes even when one resource is down
_admin.enableInstance(_clusterName, "localhost_12918", false);
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setResources(Sets.newHashSet(testDB))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
_admin.enableCluster(_clusterName, false);
_admin.enableInstance(_clusterName, "localhost_12918", true);
verifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setResources(Sets.newHashSet(testDB)).build();
Assert.assertTrue(verifier.verifyByPolling());
verifier = new StrictMatchExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setResources(Sets.newHashSet(testDB)).setDeactivatedNodeAwareness(true).build();
Assert.assertTrue(verifier.verifyByPolling());
// But the full cluster verification should fail
verifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient).build();
Assert.assertFalse(verifier.verify(3000));
verifier = new StrictMatchExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setDeactivatedNodeAwareness(true).build();
Assert.assertFalse(verifier.verify(3000));
_admin.enableCluster(_clusterName, true);
}
@Test
public void testSleepTransition() throws InterruptedException {
HelixClusterVerifier bestPossibleVerifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(bestPossibleVerifier.verify(10000));
HelixClusterVerifier strictMatchVerifier =
new StrictMatchExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setDeactivatedNodeAwareness(true)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(strictMatchVerifier.verify(10000));
// Re-start a new participant with sleeping transition(all state model transition cannot finish)
_participants[0].syncStop();
Thread.sleep(1000);
_participants[0] = new MockParticipantManager(ZK_ADDR, _clusterName, _participants[0].getInstanceName());
_participants[0].setTransition(new SleepTransition(99999999));
_participants[0].syncStart();
// The new participant causes rebalance, but the state transitions are all stuck
Assert.assertFalse(strictMatchVerifier.verify(3000));
}
}
| 9,434 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/tools/TestClusterSetup.java
|
package org.apache.helix.tools;
/*
* 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.Date;
import java.util.List;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.PropertyPathBuilder;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.cloud.azure.AzureConstants;
import org.apache.helix.cloud.constants.CloudProvider;
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.model.CloudConfig;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.LiveInstance;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestClusterSetup extends ZkUnitTestBase {
protected static final String CLUSTER_NAME = "TestClusterSetup";
protected static final String TEST_DB = "TestDB";
protected static final String INSTANCE_PREFIX = "instance_";
protected static final String STATE_MODEL = "MasterSlave";
protected static final String TEST_NODE = "testnode_1";
private ClusterSetup _clusterSetup;
private static String[] createArgs(String str) {
String[] split = str.split("[ ]+");
System.out.println(Arrays.toString(split));
return split;
}
@BeforeClass()
public void beforeClass() throws Exception {
System.out
.println("START TestClusterSetup.beforeClass() " + new Date(System.currentTimeMillis()));
_clusterSetup = new ClusterSetup(ZK_ADDR);
}
@AfterClass()
public void afterClass() {
deleteCluster(CLUSTER_NAME);
_clusterSetup.close();
System.out.println("END TestClusterSetup.afterClass() " + new Date(System.currentTimeMillis()));
}
@BeforeMethod()
public void setup() {
try {
_gZkClient.deleteRecursively("/" + CLUSTER_NAME);
_clusterSetup.addCluster(CLUSTER_NAME, true);
} catch (Exception e) {
System.out.println("@BeforeMethod TestClusterSetup exception:" + e);
}
}
private boolean testZkAdminTimeoutHelper() {
boolean exceptionThrown = false;
ZKHelixAdmin admin = null;
try {
admin = new ZKHelixAdmin("localhost:27999");
} catch (Exception e) {
exceptionThrown = true;
} finally {
if (admin != null) {
admin.close();
}
}
return exceptionThrown;
}
// Note, with mvn 3.6.1, we have a nasty bug that running "mvn test" under helix-core,
// all the bellow test will be invoked after other test including @AfterClass cleanup of this
// This bug does not happen of running command as "mvn test -Dtest=TestClusterSetup". Nor does it
// happen in intellij. The workaround found is to add dependsOnMethods attribute to all the rest.
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testZkAdminTimeout() {
boolean exceptionThrown = testZkAdminTimeoutHelper();
Assert.assertTrue(exceptionThrown);
System.setProperty(ZKHelixAdmin.CONNECTION_TIMEOUT, "3");
exceptionThrown = testZkAdminTimeoutHelper();
long time = System.currentTimeMillis();
Assert.assertTrue(exceptionThrown);
Assert.assertTrue(System.currentTimeMillis() - time < 5000);
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testAddInstancesToCluster() throws Exception {
String[] instanceAddresses = new String[3];
for (int i = 0; i < 3; i++) {
String currInstance = INSTANCE_PREFIX + i;
instanceAddresses[i] = currInstance;
}
String nextInstanceAddress = INSTANCE_PREFIX + 3;
_clusterSetup.addInstancesToCluster(CLUSTER_NAME, instanceAddresses);
// verify instances
for (String instance : instanceAddresses) {
verifyInstance(_gZkClient, CLUSTER_NAME, instance, true);
}
_clusterSetup.addInstanceToCluster(CLUSTER_NAME, nextInstanceAddress);
verifyInstance(_gZkClient, CLUSTER_NAME, nextInstanceAddress, true);
// re-add
boolean caughtException = false;
try {
_clusterSetup.addInstanceToCluster(CLUSTER_NAME, nextInstanceAddress);
} catch (HelixException e) {
caughtException = true;
}
AssertJUnit.assertTrue(caughtException);
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testDisableDropInstancesFromCluster() throws Exception {
testAddInstancesToCluster();
String[] instanceAddresses = new String[3];
for (int i = 0; i < 3; i++) {
String currInstance = INSTANCE_PREFIX + i;
instanceAddresses[i] = currInstance;
}
String nextInstanceAddress = INSTANCE_PREFIX + 3;
boolean caughtException = false;
// drop without disabling
try {
_clusterSetup.dropInstanceFromCluster(CLUSTER_NAME, nextInstanceAddress);
} catch (HelixException e) {
caughtException = true;
}
AssertJUnit.assertTrue(caughtException);
// disable
_clusterSetup.getClusterManagementTool().enableInstance(CLUSTER_NAME, nextInstanceAddress,
false);
verifyEnabled(_gZkClient, CLUSTER_NAME, nextInstanceAddress, false);
// drop
_clusterSetup.dropInstanceFromCluster(CLUSTER_NAME, nextInstanceAddress);
verifyInstance(_gZkClient, CLUSTER_NAME, nextInstanceAddress, false);
// re-drop
caughtException = false;
try {
_clusterSetup.dropInstanceFromCluster(CLUSTER_NAME, nextInstanceAddress);
} catch (HelixException e) {
caughtException = true;
}
AssertJUnit.assertTrue(caughtException);
// bad format disable, drop
String badFormatInstance = "badinstance";
caughtException = false;
try {
_clusterSetup.getClusterManagementTool().enableInstance(CLUSTER_NAME, badFormatInstance,
false);
} catch (HelixException e) {
caughtException = true;
}
AssertJUnit.assertTrue(caughtException);
caughtException = false;
try {
_clusterSetup.dropInstanceFromCluster(CLUSTER_NAME, badFormatInstance);
} catch (HelixException e) {
caughtException = true;
}
AssertJUnit.assertTrue(caughtException);
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testAddResource() throws Exception {
try {
_clusterSetup.addResourceToCluster(CLUSTER_NAME, TEST_DB, 16, STATE_MODEL);
} catch (Exception ignored) {
}
verifyResource(_gZkClient, CLUSTER_NAME, TEST_DB, true);
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testRemoveResource() throws Exception {
_clusterSetup.setupTestCluster(CLUSTER_NAME);
verifyResource(_gZkClient, CLUSTER_NAME, TEST_DB, true);
_clusterSetup.dropResourceFromCluster(CLUSTER_NAME, TEST_DB);
verifyResource(_gZkClient, CLUSTER_NAME, TEST_DB, false);
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testRebalanceCluster() throws Exception {
_clusterSetup.setupTestCluster(CLUSTER_NAME);
// testAddInstancesToCluster();
testAddResource();
_clusterSetup.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, 4);
verifyReplication(_gZkClient, CLUSTER_NAME, TEST_DB, 4);
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testParseCommandLinesArgs() throws Exception {
// wipe ZK
_gZkClient.deleteRecursively("/" + CLUSTER_NAME);
ClusterSetup
.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " --addCluster " + CLUSTER_NAME));
// wipe again
_gZkClient.deleteRecursively("/" + CLUSTER_NAME);
_clusterSetup.setupTestCluster(CLUSTER_NAME);
ClusterSetup.processCommandLineArgs(
createArgs("-zkSvr " + ZK_ADDR + " --addNode " + CLUSTER_NAME + " " + TEST_NODE));
verifyInstance(_gZkClient, CLUSTER_NAME, TEST_NODE, true);
try {
ClusterSetup.processCommandLineArgs(createArgs("-zkSvr " + ZK_ADDR + " --addResource "
+ CLUSTER_NAME + " " + TEST_DB + " 4 " + STATE_MODEL));
} catch (Exception ignored) {
}
verifyResource(_gZkClient, CLUSTER_NAME, TEST_DB, true);
// ClusterSetup
// .processCommandLineArgs(createArgs("-zkSvr "+ZK_ADDR+" --addNode node-1"));
ClusterSetup.processCommandLineArgs(createArgs(
"-zkSvr " + ZK_ADDR + " --enableInstance " + CLUSTER_NAME + " " + TEST_NODE + " true"));
verifyEnabled(_gZkClient, CLUSTER_NAME, TEST_NODE, true);
ClusterSetup.processCommandLineArgs(createArgs(
"-zkSvr " + ZK_ADDR + " --enableInstance " + CLUSTER_NAME + " " + TEST_NODE + " false"));
verifyEnabled(_gZkClient, CLUSTER_NAME, TEST_NODE, false);
ClusterSetup.processCommandLineArgs(
createArgs("-zkSvr " + ZK_ADDR + " --dropNode " + CLUSTER_NAME + " " + TEST_NODE));
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testSetGetRemoveParticipantConfig() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
_clusterSetup.addCluster(clusterName, true);
_clusterSetup.addInstanceToCluster(clusterName, "localhost_0");
// test set/get/remove instance configs
String scopeArgs = clusterName + ",localhost_0";
String keyValueMap = "key1=value1,key2=value2";
String keys = "key1,key2";
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--setConfig", ConfigScopeProperty.PARTICIPANT.toString(), scopeArgs,
keyValueMap
});
// getConfig returns json-formatted key-value pairs
String valuesStr = _clusterSetup.getConfig(ConfigScopeProperty.PARTICIPANT, scopeArgs, keys);
ZNRecordSerializer serializer = new ZNRecordSerializer();
ZNRecord record = (ZNRecord) serializer.deserialize(valuesStr.getBytes());
Assert.assertEquals(record.getSimpleField("key1"), "value1");
Assert.assertEquals(record.getSimpleField("key2"), "value2");
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--removeConfig", ConfigScopeProperty.PARTICIPANT.toString(), scopeArgs,
keys
});
valuesStr = _clusterSetup.getConfig(ConfigScopeProperty.PARTICIPANT, scopeArgs, keys);
record = (ZNRecord) serializer.deserialize(valuesStr.getBytes());
Assert.assertNull(record.getSimpleField("key1"));
Assert.assertNull(record.getSimpleField("key2"));
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testEnableCluster() 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
// pause cluster
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--enableCluster", clusterName, "false"
});
Builder keyBuilder = new Builder(clusterName);
boolean exists = _gZkClient.exists(keyBuilder.pause().getPath());
Assert.assertTrue(exists, "pause node under controller should be created");
// resume cluster
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--enableCluster", clusterName, "true"
});
exists = _gZkClient.exists(keyBuilder.pause().getPath());
Assert.assertFalse(exists, "pause node under controller should be removed");
// clean up
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testDropInstance() throws Exception {
// drop without stop, should throw exception
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
String instanceAddress = "localhost:12918";
String instanceName = "localhost_12918";
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
// add fake liveInstance
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,
new ZkBaseDataAccessor.Builder<ZNRecord>()
.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM)
.setZkClientType(ZkBaseDataAccessor.ZkClientType.DEDICATED)
.setZkAddress(ZK_ADDR)
.build());
try {
Builder keyBuilder = new Builder(clusterName);
LiveInstance liveInstance = new LiveInstance(instanceName);
liveInstance.setSessionId("session_0");
liveInstance.setHelixVersion("version_0");
Assert.assertTrue(accessor.setProperty(keyBuilder.liveInstance(instanceName), liveInstance));
// Drop instance without stopping the live instance, should throw HelixException
try {
ClusterSetup.processCommandLineArgs(
new String[]{"--zkSvr", ZK_ADDR, "--dropNode", clusterName, instanceAddress});
Assert.fail("Should throw exception since localhost_12918 is still in LIVEINSTANCES/");
} catch (HelixException expected) {
Assert.assertEquals(expected.getMessage(),
"Cannot drop instance " + instanceName + " as it is still live. Please stop it first");
}
accessor.removeProperty(keyBuilder.liveInstance(instanceName));
// drop without disable, should throw exception
try {
ClusterSetup.processCommandLineArgs(
new String[]{"--zkSvr", ZK_ADDR, "--dropNode", clusterName, instanceAddress});
Assert.fail("Should throw exception since " + instanceName + " is enabled");
} catch (HelixException expected) {
Assert.assertEquals(expected.getMessage(),
"Node " + instanceName + " is enabled, cannot drop");
}
// Disable the instance
ClusterSetup.processCommandLineArgs(
new String[]{"--zkSvr", ZK_ADDR, "--enableInstance", clusterName, instanceName, "false"});
// Drop the instance
ClusterSetup.processCommandLineArgs(
new String[]{"--zkSvr", ZK_ADDR, "--dropNode", clusterName, instanceAddress});
Assert.assertNull(accessor.getProperty(keyBuilder.instanceConfig(instanceName)),
"Instance config should be dropped");
Assert.assertFalse(_gZkClient.exists(PropertyPathBuilder.instance(clusterName, instanceName)),
"Instance/host should be dropped");
} finally {
// Have to close the dedicated zkclient in accessor to avoid zkclient leakage.
accessor.getBaseDataAccessor().close();
TestHelper.dropCluster(clusterName, _gZkClient);
// Verify the cluster has been dropped.
Assert.assertTrue(TestHelper.verify(() -> {
if (_gZkClient.exists("/" + clusterName)) {
TestHelper.dropCluster(clusterName, _gZkClient);
}
return true;
}, TestHelper.WAIT_DURATION));
}
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testDisableResource() 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
"MasterSlave", true); // do rebalance
// disable "TestDB0" resource
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--enableResource", clusterName, "TestDB0", "false"
});
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(ZK_ADDR);
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
Assert.assertFalse(idealState.isEnabled());
// enable "TestDB0" resource
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--enableResource", clusterName, "TestDB0", "true"
});
idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
Assert.assertTrue(idealState.isEnabled());
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test(expectedExceptions = HelixException.class)
public void testAddClusterWithInvalidCloudConfig() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder();
cloudConfigInitBuilder.setCloudEnabled(true);
List<String> sourceList = new ArrayList<String>();
sourceList.add("TestURL");
cloudConfigInitBuilder.setCloudInfoSources(sourceList);
cloudConfigInitBuilder.setCloudProvider(CloudProvider.CUSTOMIZED);
CloudConfig cloudConfigInit = cloudConfigInitBuilder.build();
// Since setCloudInfoProcessorName is missing, this add cluster call will throw an exception
_clusterSetup.addCluster(clusterName, false, cloudConfigInit);
}
@Test(dependsOnMethods = "testAddClusterWithInvalidCloudConfig")
public void testAddClusterWithValidCloudConfig() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder();
cloudConfigInitBuilder.setCloudEnabled(true);
cloudConfigInitBuilder.setCloudID("TestID");
List<String> sourceList = new ArrayList<String>();
sourceList.add("TestURL");
cloudConfigInitBuilder.setCloudInfoSources(sourceList);
cloudConfigInitBuilder.setCloudInfoProcessorName("TestProcessorName");
cloudConfigInitBuilder.setCloudProvider(CloudProvider.CUSTOMIZED);
CloudConfig cloudConfigInit = cloudConfigInitBuilder.build();
_clusterSetup.addCluster(clusterName, false, cloudConfigInit);
// Read CloudConfig from Zookeeper and check the content
ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient);
CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertTrue(cloudConfigFromZk.isCloudEnabled());
Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestID");
List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources();
Assert.assertEquals(listUrlFromZk.get(0), "TestURL");
Assert.assertEquals(cloudConfigFromZk.getCloudInfoProcessorName(), "TestProcessorName");
Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.CUSTOMIZED.name());
}
@Test(dependsOnMethods = "testAddClusterWithInvalidCloudConfig",
expectedExceptions = HelixException.class)
public void testAddClusterWithFailure() throws Exception {
HelixAdmin admin = mock(HelixAdmin.class);
when(admin.addCluster(anyString(), anyBoolean())).thenReturn(Boolean.FALSE);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder();
cloudConfigInitBuilder.setCloudEnabled(true);
List<String> sourceList = new ArrayList<String>();
sourceList.add("TestURL");
cloudConfigInitBuilder.setCloudInfoSources(sourceList);
cloudConfigInitBuilder.setCloudProvider(CloudProvider.CUSTOMIZED);
CloudConfig cloudConfigInit = cloudConfigInitBuilder.build();
// Since setCloudInfoProcessorName is missing, this add cluster call will throw an exception
_clusterSetup.addCluster(clusterName, false, cloudConfigInit);
}
@Test(dependsOnMethods = "testAddClusterWithValidCloudConfig")
public void testAddClusterAzureProvider() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder();
cloudConfigInitBuilder.setCloudEnabled(true);
cloudConfigInitBuilder.setCloudID("TestID");
cloudConfigInitBuilder.setCloudProvider(CloudProvider.AZURE);
CloudConfig cloudConfigInit = cloudConfigInitBuilder.build();
_clusterSetup.addCluster(clusterName, false, cloudConfigInit);
// Read CloudConfig from Zookeeper and check the content
ConfigAccessor _configAccessor = new ConfigAccessor(ZK_ADDR);
CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertTrue(cloudConfigFromZk.isCloudEnabled());
Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestID");
List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources();
// Since it is Azure, topology information should have been populated.
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(clusterName);
Assert.assertEquals(clusterConfig.getTopology(), AzureConstants.AZURE_TOPOLOGY);
Assert.assertEquals(clusterConfig.getFaultZoneType(), AzureConstants.AZURE_FAULT_ZONE_TYPE);
Assert.assertTrue(clusterConfig.isTopologyAwareEnabled());
// Since provider is not customized, CloudInfoSources and CloudInfoProcessorName will be null.
Assert.assertNull(listUrlFromZk);
Assert.assertNull(cloudConfigFromZk.getCloudInfoProcessorName());
Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.AZURE.name());
}
@Test(dependsOnMethods = "testAddClusterAzureProvider")
public void testSetRemoveCloudConfig() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
// Create Cluster without cloud config
_clusterSetup.addCluster(clusterName, false);
// Read CloudConfig from Zookeeper and check the content
ConfigAccessor _configAccessor = new ConfigAccessor(ZK_ADDR);
CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertNull(cloudConfigFromZk);
String cloudConfigManifest =
"{\"simpleFields\" : {\"CLOUD_ENABLED\" : \"true\",\"CLOUD_PROVIDER\": \"AZURE\"}}\"";
_clusterSetup.setCloudConfig(clusterName, cloudConfigManifest);
// Read cloud config from ZK and make sure the fields are accurate
cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertNotNull(cloudConfigFromZk);
Assert.assertEquals(CloudProvider.AZURE.name(), cloudConfigFromZk.getCloudProvider());
Assert.assertTrue(cloudConfigFromZk.isCloudEnabled());
// Remove cloud config and make sure it has been removed
_clusterSetup.removeCloudConfig(clusterName);
cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName);
Assert.assertNull(cloudConfigFromZk);
}
}
| 9,435 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/tools/TestClusterStateVerifier.java
|
package org.apache.helix.tools;
/*
* 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 com.google.common.collect.Sets;
import org.apache.helix.HelixAdmin;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkUnitTestBase;
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.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Deprecated
public class TestClusterStateVerifier extends ZkUnitTestBase {
final String[] RESOURCES = {
"resource0", "resource1"
};
private HelixAdmin _admin;
private MockParticipantManager[] _participants;
private ClusterControllerManager _controller;
private String _clusterName;
@BeforeMethod
public void beforeMethod() throws InterruptedException {
final int NUM_PARTITIONS = 1;
final int NUM_REPLICAS = 1;
// Cluster and resource setup
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
_clusterName = className + "_" + methodName;
_admin = _gSetupTool.getClusterManagementTool();
_gSetupTool.addCluster(_clusterName, true);
_gSetupTool.addResourceToCluster(_clusterName, RESOURCES[0], NUM_PARTITIONS, "OnlineOffline",
RebalanceMode.SEMI_AUTO.toString());
_gSetupTool.addResourceToCluster(_clusterName, RESOURCES[1], NUM_PARTITIONS, "OnlineOffline",
RebalanceMode.SEMI_AUTO.toString());
// Configure and start the participants
_participants = new MockParticipantManager[RESOURCES.length];
for (int i = 0; i < _participants.length; i++) {
String host = "localhost";
int port = 12918 + i;
String id = host + '_' + port;
_gSetupTool.addInstanceToCluster(_clusterName, id);
_participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, id);
_participants[i].syncStart();
}
// Rebalance the resources
for (int i = 0; i < RESOURCES.length; i++) {
IdealState idealState = _admin.getResourceIdealState(_clusterName, RESOURCES[i]);
idealState.setReplicas(Integer.toString(NUM_REPLICAS));
idealState.getRecord().setListField(RESOURCES[i] + "_0",
Arrays.asList(_participants[i].getInstanceName()));
_admin.setResourceIdealState(_clusterName, RESOURCES[i], idealState);
}
// Start the controller
_controller = new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
_controller.syncStart();
Thread.sleep(1000);
}
@AfterMethod
public void afterMethod() {
// Cleanup
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
_admin.dropCluster(_clusterName);
}
@Test
public void testEntireCluster() {
// Just ensure that the entire cluster passes
// ensure that the external view coalesces
BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName);
try {
boolean result = ClusterStateVerifier.verifyByZkCallback(verifier);
Assert.assertTrue(result);
} finally {
verifier.close();
}
}
@Test
public void testResourceSubset() throws InterruptedException {
// Ensure that this passes even when one resource is down
_admin.enableInstance(_clusterName, "localhost_12918", false);
Thread.sleep(1000);
_admin.enableCluster(_clusterName, false);
_admin.enableInstance(_clusterName, "localhost_12918", true);
BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR,
_clusterName, null, Sets.newHashSet(RESOURCES[1]));
boolean result = false;
try {
result = ClusterStateVerifier.verifyByZkCallback(verifier);
Assert.assertTrue(result);
} finally {
verifier.close();
}
String[] args = {
"--zkSvr", ZK_ADDR, "--cluster", _clusterName, "--resources", RESOURCES[1]
};
result = ClusterStateVerifier.verifyState(args);
Assert.assertTrue(result);
// But the full cluster verification should fail
verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName);
try {
boolean fullResult = verifier.verify();
Assert.assertFalse(fullResult);
} finally {
verifier.close();
}
_admin.enableCluster(_clusterName, true);
}
}
| 9,436 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/tools
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/tools/ClusterVerifiers/TestStrictMatchExternalViewVerifier.java
|
package org.apache.helix.tools.ClusterVerifiers;
/*
* 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.List;
import java.util.Map;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.util.HelixUtil;
import org.apache.helix.util.TestInputLoader;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestStrictMatchExternalViewVerifier {
@Test(dataProvider = "TestComputeIdealMappingInput")
public void testComputeIdealMapping(String comment, String stateModelName,
List<String> preferenceList, List<String> liveAndEnabledInstances,
Map<String, String> expectedIdealMapping) {
System.out.println("Test case comment: " + comment);
Map<String, String> idealMapping = HelixUtil.computeIdealMapping(preferenceList,
BuiltInStateModelDefinitions.valueOf(stateModelName).getStateModelDefinition(),
new HashSet<>(liveAndEnabledInstances));
Assert.assertTrue(idealMapping.equals(expectedIdealMapping));
}
@DataProvider(name = "TestComputeIdealMappingInput")
public Object[][] loadTestComputeIdealMappingInput() {
final String[] params = { "comment", "stateModel", "preferenceList", "liveAndEnabledInstances",
"expectedBestPossibleStateMap"
};
return TestInputLoader
.loadTestInputs("TestStrictMatchExternalViewVerifier.ComputeIdealMapping.json", params);
}
}
| 9,437 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/util/TestZKClientPool.java
|
package org.apache.helix.util;
/*
* 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.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.apache.helix.zookeeper.zkclient.ZkServer;
import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestZKClientPool {
@Test
public void test() throws Exception {
String testName = "TestZKClientPool";
System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis()));
String zkAddr = "localhost:21891";
ZkServer zkServer = TestHelper.startZkServer(zkAddr);
ZkClient zkClient = ZKClientPool.getZkClient(zkAddr);
zkClient.createPersistent("/" + testName, new ZNRecord(testName));
ZNRecord record = zkClient.readData("/" + testName);
Assert.assertEquals(record.getId(), testName);
TestHelper.stopZkServer(zkServer);
// restart zk
zkServer = TestHelper.startZkServer(zkAddr);
try {
zkClient = ZKClientPool.getZkClient(zkAddr);
record = zkClient.readData("/" + testName);
Assert.fail("should fail on zk no node exception");
} catch (ZkNoNodeException e) {
// OK
} catch (Exception e) {
Assert.fail("should not fail on exception other than ZkNoNodeException");
}
zkClient.createPersistent("/" + testName, new ZNRecord(testName));
record = zkClient.readData("/" + testName);
Assert.assertEquals(record.getId(), testName);
zkClient.close();
TestHelper.stopZkServer(zkServer);
System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,438 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/util/TestStatusUpdateUtil.java
|
package org.apache.helix.util;
/*
* 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.reflect.Field;
import java.lang.reflect.Modifier;
import org.apache.helix.HelixConstants;
import org.apache.helix.PropertyPathBuilder;
import org.apache.helix.SystemPropertyKeys;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.messaging.handling.HelixStateTransitionHandler;
import org.apache.helix.model.Message;
import org.apache.helix.model.StatusUpdate;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.zkclient.exception.ZkException;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestStatusUpdateUtil extends ZkTestBase {
private String clusterName = TestHelper.getTestClassName();
private int n = 1;
private Message message = new Message(Message.MessageType.STATE_TRANSITION, "Some unique id");
private MockParticipantManager[] participants = new MockParticipantManager[n];
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
@AfterClass
public void afterClass() {
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
}
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
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);
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
message.setSrcName("cm-instance-0");
message.setTgtSessionId(participants[0].getSessionId());
message.setFromState("Offline");
message.setToState("Slave");
message.setPartitionName("TestDB_0");
message.setMsgId("Some unique message id");
message.setResourceName("TestDB");
message.setTgtName("localhost_12918");
message.setStateModelDef("MasterSlave");
message.setStateModelFactoryName(HelixConstants.DEFAULT_STATE_MODEL_FACTORY);
}
@Test(dependsOnMethods = "testDisableErrorLogByDefault")
public void testEnableErrorLog() throws Exception {
StatusUpdateUtil statusUpdateUtil = new StatusUpdateUtil();
setFinalStatic(StatusUpdateUtil.class.getField("ERROR_LOG_TO_ZK_ENABLED"), true);
Exception e = new RuntimeException("test exception");
statusUpdateUtil.logError(message, HelixStateTransitionHandler.class, e,
"test status update", participants[0]);
// logged to Zookeeper
String errPath = PropertyPathBuilder
.instanceError(clusterName, "localhost_12918", participants[0].getSessionId(), "TestDB",
"TestDB_0");
try {
ZNRecord error = _gZkClient.readData(errPath);
} catch (ZkException zke) {
Assert.fail("expecting being able to send error logs to ZK.", zke);
}
}
@Test
public void testDisableErrorLogByDefault() throws Exception {
StatusUpdateUtil statusUpdateUtil = new StatusUpdateUtil();
setFinalStatic(StatusUpdateUtil.class.getField("ERROR_LOG_TO_ZK_ENABLED"), false);
Exception e = new RuntimeException("test exception");
statusUpdateUtil.logError(message, HelixStateTransitionHandler.class, e,
"test status update", participants[0]);
// assert by default, not logged to Zookeeper
String errPath = PropertyPathBuilder
.instanceError(clusterName, "localhost_12918", participants[0].getSessionId(), "TestDB",
"TestDB_0");
try {
ZNRecord error = _gZkClient.readData(errPath);
Assert.fail("not expecting being able to send error logs to ZK by default.");
} catch (ZkException zke) {
// expected
}
}
}
| 9,439 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/util/TestIdealStateAssignment.java
|
package org.apache.helix.util;
/*
* 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.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestIdealStateAssignment {
private static final String fileNamePrefix = "TestIdealStateAssignment";
@Test(dataProvider = "IdealStateInput")
public void testIdealStateAssignment(String clusterName, List<String> instances,
List<String> partitions, String numReplicas, String stateModeDef, String strategyName,
Map<String, Map<String, String>> expectedMapping, List<String> disabledInstances)
throws IllegalAccessException, InstantiationException, ClassNotFoundException {
ClusterConfig clusterConfig = new ClusterConfig(clusterName);
List<InstanceConfig> instanceConfigs = new ArrayList<>();
for (String instance : instances) {
instanceConfigs.add(new InstanceConfig(instance));
if (disabledInstances.contains(instance)) {
instanceConfigs.get(instanceConfigs.size() - 1).setInstanceEnabled(false);
}
}
IdealState idealState = new IdealState("TestResource");
idealState.setStateModelDefRef(stateModeDef);
idealState.setNumPartitions(partitions.size());
idealState.setReplicas(numReplicas);
Map<String, Map<String, String>> idealStateMapping = HelixUtil
.getIdealAssignmentForFullAuto(clusterConfig, instanceConfigs, instances, idealState,
partitions, strategyName);
Assert.assertEquals(idealStateMapping, expectedMapping);
}
@DataProvider(name = "IdealStateInput")
public Object[][] getIdealStateInput() {
final String[] inputs =
{ "ClusterName", "Instances", "Partitions", "NumReplica", "StateModelDef", "StrategyName",
"ExpectedMapping", "DisabledInstances"
};
return TestInputLoader.loadTestInputs(fileNamePrefix + ".NoIdealState.json", inputs);
}
}
| 9,440 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/util/TestInputLoader.java
|
package org.apache.helix.util;
/*
* 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.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
public class TestInputLoader {
public static Object[][] loadTestInputs(String inputFile, String[] params) {
List<Object[]> data = new ArrayList<Object[]>();
InputStream inputStream = TestInputLoader.class.getClassLoader().getResourceAsStream(inputFile);
try {
ObjectReader mapReader = new ObjectMapper().reader(Map[].class);
Map[] inputs = mapReader.readValue(inputStream);
for (Map input : inputs) {
Object[] objects = new Object[params.length];
for (int i = 0; i < params.length; i++) {
objects[i] = input.get(params[i]);
}
data.add(objects);
}
} catch (IOException e) {
e.printStackTrace();
}
Object[][] ret = new Object[data.size()][];
for(int i = 0; i < data.size(); i++) {
ret[i] = data.get(i);
}
return ret;
}
}
| 9,441 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/util/TestPropertyKeyGetPath.java
|
package org.apache.helix.util;
/*
* 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.base.Joiner;
import org.apache.helix.AccessOption;
import org.apache.helix.PropertyKey;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.task.TaskConstants;
import org.apache.helix.task.WorkflowContext;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestPropertyKeyGetPath extends TaskTestBase {
private static final String WORKFLOW_NAME = "testWorkflow_01";
private static final String JOB_NAME = "testJob_01";
private static final String CONFIGS_NODE = "CONFIGS";
private static final String RESOURCE_NODE = "RESOURCE";
private static final String CONTEXT_NODE = "Context";
private static final String TASK_FRAMEWORK_CONTEXT_NODE = "TaskRebalancer";
private static final String PROPERTYSTORE_NODE = "PROPERTYSTORE";
private PropertyKey.Builder KEY_BUILDER = new PropertyKey.Builder(CLUSTER_NAME);
/**
* This test method tests whether PropertyKey.Builder successfully creates a path for
* WorkflowContext instances.
* TODO: KeyBuilder must handle the case for future versions of Task Framework with a different
* path structure
*/
@Test
public void testGetWorkflowContext() {
// Manually create a WorkflowContext instance
ZNRecord znRecord = new ZNRecord(WORKFLOW_NAME);
WorkflowContext workflowContext = new WorkflowContext(znRecord);
_manager.getHelixPropertyStore().set(
Joiner.on("/").join(TaskConstants.REBALANCER_CONTEXT_ROOT, WORKFLOW_NAME, CONTEXT_NODE),
workflowContext.getRecord(), AccessOption.PERSISTENT);
// Test retrieving this WorkflowContext using PropertyKey.Builder.getPath()
String path = KEY_BUILDER.workflowContext(WORKFLOW_NAME).getPath();
WorkflowContext workflowCtx =
new WorkflowContext(_baseAccessor.get(path, null, AccessOption.PERSISTENT));
Assert.assertEquals(workflowContext, workflowCtx);
}
/**
* Tests if the new KeyBuilder APIs for generating workflow and job config/context paths are
* working properly.
*/
@Test
public void testTaskFrameworkPropertyKeys() {
String taskConfigRoot = "/" + Joiner.on("/").join(CLUSTER_NAME, CONFIGS_NODE, RESOURCE_NODE);
String workflowConfig = "/"
+ Joiner.on("/").join(CLUSTER_NAME, CONFIGS_NODE, RESOURCE_NODE, WORKFLOW_NAME);
String jobConfig = "/" + Joiner.on("/").join(CLUSTER_NAME, CONFIGS_NODE, RESOURCE_NODE,
WORKFLOW_NAME + "_" + JOB_NAME);
String taskContextRoot =
"/" + Joiner.on("/").join(CLUSTER_NAME, PROPERTYSTORE_NODE, TASK_FRAMEWORK_CONTEXT_NODE);
String workflowContext = "/" + Joiner.on("/").join(CLUSTER_NAME, PROPERTYSTORE_NODE,
TASK_FRAMEWORK_CONTEXT_NODE, WORKFLOW_NAME, CONTEXT_NODE);
String jobContext = "/" + Joiner.on("/").join(CLUSTER_NAME, PROPERTYSTORE_NODE,
TASK_FRAMEWORK_CONTEXT_NODE, WORKFLOW_NAME + "_" + JOB_NAME, CONTEXT_NODE);
Assert.assertEquals(KEY_BUILDER.workflowConfigZNodes().getPath(), taskConfigRoot);
Assert.assertEquals(KEY_BUILDER.workflowConfigZNode(WORKFLOW_NAME).getPath(), workflowConfig);
Assert.assertEquals(KEY_BUILDER.jobConfigZNode(WORKFLOW_NAME, JOB_NAME).getPath(), jobConfig);
Assert.assertEquals(KEY_BUILDER.workflowContextZNodes().getPath(), taskContextRoot);
Assert.assertEquals(KEY_BUILDER.workflowContextZNode(WORKFLOW_NAME).getPath(), workflowContext);
Assert.assertEquals(KEY_BUILDER.jobContextZNode(WORKFLOW_NAME, JOB_NAME).getPath(), jobContext);
}
}
| 9,442 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/util/TestInstanceValidationUtil.java
|
package org.apache.helix.util;
/*
* 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 com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyType;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.StateModelDefinition;
import org.mockito.ArgumentMatcher;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestInstanceValidationUtil {
private static final String TEST_CLUSTER = "testCluster";
private static final String TEST_INSTANCE = "instance0";
private static final PropertyKey.Builder BUILDER = new PropertyKey.Builder(TEST_CLUSTER);
@DataProvider
Object[][] isEnabledTestSuite() {
return new Object[][] {
{
true, true, true
}, {
true, false, false
}, {
false, true, false
}, {
false, false, false
}
};
}
@Test(dataProvider = "isEnabledTestSuite", enabled = false)
public void TestIsInstanceEnabled(boolean instanceConfigEnabled, boolean clusterConfigEnabled,
boolean expected) {
Mock mock = new Mock();
InstanceConfig instanceConfig = new InstanceConfig(TEST_INSTANCE);
instanceConfig.setInstanceEnabled(instanceConfigEnabled);
doReturn(instanceConfig).when(mock.dataAccessor)
.getProperty(BUILDER.instanceConfig(TEST_INSTANCE));
ClusterConfig clusterConfig = new ClusterConfig(TEST_CLUSTER);
if (!clusterConfigEnabled) {
clusterConfig.setDisabledInstances(ImmutableMap.of(TEST_INSTANCE, "12345"));
}
doReturn(clusterConfig).when(mock.dataAccessor)
.getProperty(BUILDER.clusterConfig());
boolean isEnabled = InstanceValidationUtil.isEnabled(mock.dataAccessor, TEST_INSTANCE);
Assert.assertEquals(isEnabled, expected);
}
@Test(expectedExceptions = HelixException.class)
public void TestIsInstanceEnabled_whenInstanceConfigNull() {
Mock mock = new Mock();
doReturn(null).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CONFIGS)));
InstanceValidationUtil.isEnabled(mock.dataAccessor, TEST_INSTANCE);
}
@Test(expectedExceptions = HelixException.class)
public void TestIsInstanceEnabled_whenClusterConfigNull() {
Mock mock = new Mock();
doReturn(new InstanceConfig(TEST_INSTANCE)).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CONFIGS)));
doReturn(null).when(mock.dataAccessor)
.getProperty(BUILDER.clusterConfig());
InstanceValidationUtil.isEnabled(mock.dataAccessor, TEST_INSTANCE);
}
@Test
public void TestIsInstanceAlive() {
Mock mock = new Mock();
doReturn(new LiveInstance(TEST_INSTANCE)).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.LIVEINSTANCES)));
Assert.assertTrue(InstanceValidationUtil.isAlive(mock.dataAccessor, TEST_INSTANCE));
}
@Test
public void TestHasResourceAssigned_success() {
String sessionId = "sessionId";
String resource = "db";
Mock mock = new Mock();
LiveInstance liveInstance = new LiveInstance(TEST_INSTANCE);
liveInstance.setSessionId(sessionId);
doReturn(liveInstance).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.LIVEINSTANCES)));
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
CurrentState currentState = mock(CurrentState.class);
when(currentState.getPartitionStateMap()).thenReturn(ImmutableMap.of("db0", "master"));
doReturn(currentState).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
Assert.assertTrue(
InstanceValidationUtil.isResourceAssigned(mock.dataAccessor, TEST_INSTANCE));
}
@Test
public void TestHasResourceAssigned_fail() {
String sessionId = "sessionId";
String resource = "db";
Mock mock = new Mock();
LiveInstance liveInstance = new LiveInstance(TEST_INSTANCE);
liveInstance.setSessionId(sessionId);
doReturn(liveInstance).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.LIVEINSTANCES)));
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
CurrentState currentState = mock(CurrentState.class);
when(currentState.getPartitionStateMap()).thenReturn(Collections.<String, String> emptyMap());
doReturn(currentState).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
Assert.assertFalse(
InstanceValidationUtil.isResourceAssigned(mock.dataAccessor, TEST_INSTANCE));
}
@Test
public void TestHasResourceAssigned_whenNotAlive() {
Mock mock = new Mock();
doReturn(null).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.LIVEINSTANCES)));
Assert.assertFalse(
InstanceValidationUtil.isResourceAssigned(mock.dataAccessor, TEST_INSTANCE));
}
@Test
public void TestHasDisabledPartitions_false() {
Mock mock = new Mock();
InstanceConfig instanceConfig = mock(InstanceConfig.class);
when(instanceConfig.getDisabledPartitionsMap())
.thenReturn(Collections.<String, List<String>> emptyMap());
when(mock.dataAccessor.getProperty(any(PropertyKey.class))).thenReturn(instanceConfig);
Assert.assertFalse(InstanceValidationUtil.hasDisabledPartitions(mock.dataAccessor, TEST_CLUSTER,
TEST_INSTANCE));
}
@Test
public void TestHasDisabledPartitions_with_only_names() {
Mock mock = new Mock();
InstanceConfig instanceConfig = mock(InstanceConfig.class);
when(instanceConfig.getDisabledPartitionsMap())
.thenReturn(ImmutableMap.of("db0", Collections.emptyList()));
when(mock.dataAccessor.getProperty(any(PropertyKey.class))).thenReturn(instanceConfig);
Assert.assertFalse(InstanceValidationUtil.hasDisabledPartitions(mock.dataAccessor, TEST_CLUSTER,
TEST_INSTANCE));
}
@Test
public void TestHasDisabledPartitions_true() {
Mock mock = new Mock();
InstanceConfig instanceConfig = mock(InstanceConfig.class);
when(instanceConfig.getDisabledPartitionsMap())
.thenReturn(ImmutableMap.of("db0", Arrays.asList("p1")));
when(mock.dataAccessor.getProperty(any(PropertyKey.class))).thenReturn(instanceConfig);
Assert.assertTrue(InstanceValidationUtil.hasDisabledPartitions(mock.dataAccessor, TEST_CLUSTER,
TEST_INSTANCE));
}
@Test(expectedExceptions = HelixException.class)
public void TestHasDisabledPartitions_exception() {
Mock mock = new Mock();
when(mock.dataAccessor.getProperty(any(PropertyKey.class))).thenReturn(null);
Assert.assertTrue(InstanceValidationUtil.hasDisabledPartitions(mock.dataAccessor, TEST_CLUSTER,
TEST_INSTANCE));
}
@Test
public void TestHasValidConfig_true() {
Mock mock = new Mock();
PropertyKey.Builder keyBuilder = mock.dataAccessor.keyBuilder();
PropertyKey clusterProperty = keyBuilder.clusterConfig();
ClusterConfig clusterConfig = new ClusterConfig(TEST_CLUSTER);
clusterConfig.setPersistIntermediateAssignment(true);
when(mock.dataAccessor.getProperty(eq(clusterProperty)))
.thenReturn(clusterConfig);
PropertyKey instanceProperty = keyBuilder.instanceConfig(TEST_INSTANCE);
when(mock.dataAccessor.getProperty(eq(instanceProperty)))
.thenReturn(new InstanceConfig(TEST_INSTANCE));
Assert.assertTrue(
InstanceValidationUtil.hasValidConfig(mock.dataAccessor, TEST_CLUSTER, TEST_INSTANCE));
}
@Test
public void TestHasValidConfig_false() {
Mock mock = new Mock();
when(mock.dataAccessor.getProperty(any(PropertyKey.class))).thenReturn(null);
Assert.assertFalse(
InstanceValidationUtil.hasValidConfig(mock.dataAccessor, TEST_CLUSTER, TEST_INSTANCE));
}
@Test
public void TestHasErrorPartitions_true() {
String sessionId = "sessionId";
String resource = "db";
Mock mock = new Mock();
LiveInstance liveInstance = new LiveInstance(TEST_INSTANCE);
liveInstance.setSessionId(sessionId);
doReturn(liveInstance).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.LIVEINSTANCES)));
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
CurrentState currentState = mock(CurrentState.class);
when(currentState.getPartitionStateMap()).thenReturn(ImmutableMap.of("db0", "ERROR"));
doReturn(currentState).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
Assert.assertTrue(
InstanceValidationUtil.hasErrorPartitions(mock.dataAccessor, TEST_CLUSTER, TEST_INSTANCE));
}
@Test
public void TestHasErrorPartitions_false() {
String sessionId = "sessionId";
String resource = "db";
Mock mock = new Mock();
LiveInstance liveInstance = new LiveInstance(TEST_INSTANCE);
liveInstance.setSessionId(sessionId);
doReturn(liveInstance).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.LIVEINSTANCES)));
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
CurrentState currentState = mock(CurrentState.class);
when(currentState.getPartitionStateMap()).thenReturn(ImmutableMap.of("db0", "Master"));
doReturn(currentState).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CURRENTSTATES)));
Assert.assertFalse(
InstanceValidationUtil.hasErrorPartitions(mock.dataAccessor, TEST_CLUSTER, TEST_INSTANCE));
}
@Test
public void TestIsInstanceStable_NoException_whenPersistAssignmentOff() {
Mock mock = new Mock();
ClusterConfig clusterConfig = new ClusterConfig(TEST_CLUSTER);
clusterConfig.setPersistIntermediateAssignment(false);
when(mock.dataAccessor.getProperty(any(PropertyKey.class))).thenReturn(clusterConfig);
InstanceValidationUtil.isInstanceStable(mock.dataAccessor, TEST_INSTANCE);
}
@Test(expectedExceptions = HelixException.class)
public void TestIsInstanceStable_exception_whenExternalViewNull() {
String resource = "db";
Mock mock = new Mock();
ClusterConfig clusterConfig = new ClusterConfig(TEST_CLUSTER);
clusterConfig.setPersistIntermediateAssignment(true);
doReturn(clusterConfig).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CONFIGS)));
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
IdealState idealState = mock(IdealState.class);
when(idealState.isEnabled()).thenReturn(true);
when(idealState.getPartitionSet()).thenReturn(ImmutableSet.of("db0"));
when(idealState.getInstanceStateMap("db0"))
.thenReturn(ImmutableMap.of(TEST_INSTANCE, "Master"));
when(idealState.isValid()).thenReturn(true);
when(idealState.getStateModelDefRef()).thenReturn("MasterSlave");
doReturn(idealState).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
doReturn(null).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
InstanceValidationUtil.isInstanceStable(mock.dataAccessor, TEST_INSTANCE);
}
@Test
public void TestIsInstanceStable_true() {
String resource = "db";
Mock mock = new Mock();
ClusterConfig clusterConfig = new ClusterConfig(TEST_CLUSTER);
clusterConfig.setPersistIntermediateAssignment(true);
doReturn(clusterConfig).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CONFIGS)));
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
IdealState idealState = mock(IdealState.class);
when(idealState.isEnabled()).thenReturn(Boolean.TRUE);
when(idealState.getPartitionSet()).thenReturn(ImmutableSet.of("db0"));
when(idealState.getInstanceStateMap("db0"))
.thenReturn(ImmutableMap.of(TEST_INSTANCE, "Master"));
idealState.setInstanceStateMap("db0", ImmutableMap.of(TEST_INSTANCE, "Master"));
doReturn(idealState).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
ExternalView externalView = new ExternalView(resource);
externalView.setStateMap("db0", ImmutableMap.of(TEST_INSTANCE, "Master"));
doReturn(externalView).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
boolean result = InstanceValidationUtil.isInstanceStable(mock.dataAccessor, TEST_INSTANCE);
Assert.assertTrue(result);
}
@Test(description = "IdealState: slave state, ExternalView:Master state")
public void TestIsInstanceStable_false() {
String resource = "db";
Mock mock = new Mock();
ClusterConfig clusterConfig = new ClusterConfig(TEST_CLUSTER);
clusterConfig.setPersistIntermediateAssignment(true);
doReturn(clusterConfig).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.CONFIGS)));
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
IdealState idealState = mock(IdealState.class);
when(idealState.isEnabled()).thenReturn(true);
when(idealState.getPartitionSet()).thenReturn(ImmutableSet.of("db0"));
when(idealState.getInstanceStateMap("db0")).thenReturn(ImmutableMap.of(TEST_INSTANCE, "slave"));
when(idealState.isValid()).thenReturn(true);
when(idealState.getStateModelDefRef()).thenReturn("MasterSlave");
doReturn(idealState).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
ExternalView externalView = new ExternalView(resource);
externalView.setStateMap("db0", ImmutableMap.of(TEST_INSTANCE, "Master"));
doReturn(externalView).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
boolean result = InstanceValidationUtil.isInstanceStable(mock.dataAccessor, TEST_INSTANCE);
Assert.assertFalse(result);
}
@Test
public void TestSiblingNodesActiveReplicaCheck_success() {
String resource = "resource";
Mock mock = new Mock();
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
// set ideal state
IdealState idealState = mock(IdealState.class);
when(idealState.isEnabled()).thenReturn(true);
when(idealState.isValid()).thenReturn(true);
when(idealState.getStateModelDefRef()).thenReturn("MasterSlave");
doReturn(idealState).when(mock.dataAccessor).getProperty(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
// set external view
ExternalView externalView = mock(ExternalView.class);
when(externalView.getMinActiveReplicas()).thenReturn(2);
when(externalView.getStateModelDefRef()).thenReturn("MasterSlave");
when(externalView.getPartitionSet()).thenReturn(ImmutableSet.of("db0"));
when(externalView.getStateMap("db0")).thenReturn(ImmutableMap.of(TEST_INSTANCE, "Master",
"instance1", "Slave", "instance2", "Slave", "instance3", "Slave"));
doReturn(externalView).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
StateModelDefinition stateModelDefinition = mock(StateModelDefinition.class);
when(stateModelDefinition.getInitialState()).thenReturn("OFFLINE");
doReturn(stateModelDefinition).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.STATEMODELDEFS)));
boolean result =
InstanceValidationUtil.siblingNodesActiveReplicaCheck(mock.dataAccessor, TEST_INSTANCE);
Assert.assertTrue(result);
}
@Test
public void TestSiblingNodesActiveReplicaCheck_fail() {
String resource = "resource";
Mock mock = new Mock();
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
// set ideal state
IdealState idealState = mock(IdealState.class);
when(idealState.isEnabled()).thenReturn(true);
when(idealState.isValid()).thenReturn(true);
when(idealState.getStateModelDefRef()).thenReturn("MasterSlave");
doReturn(idealState).when(mock.dataAccessor).getProperty(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
ExternalView externalView = mock(ExternalView.class);
when(externalView.getMinActiveReplicas()).thenReturn(3);
when(externalView.getStateModelDefRef()).thenReturn("MasterSlave");
when(externalView.getPartitionSet()).thenReturn(ImmutableSet.of("db0"));
when(externalView.getStateMap("db0")).thenReturn(
ImmutableMap.of(TEST_INSTANCE, "Master", "instance1", "Slave", "instance2", "Slave"));
doReturn(externalView).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
StateModelDefinition stateModelDefinition = mock(StateModelDefinition.class);
when(stateModelDefinition.getInitialState()).thenReturn("OFFLINE");
doReturn(stateModelDefinition).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.STATEMODELDEFS)));
boolean result =
InstanceValidationUtil.siblingNodesActiveReplicaCheck(mock.dataAccessor, TEST_INSTANCE);
Assert.assertFalse(result);
}
@Test
public void TestSiblingNodesActiveReplicaCheck_whenNoMinActiveReplica() {
String resource = "resource";
Mock mock = new Mock();
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
// set ideal state
IdealState idealState = mock(IdealState.class);
when(idealState.isEnabled()).thenReturn(true);
when(idealState.isValid()).thenReturn(true);
when(idealState.getStateModelDefRef()).thenReturn("MasterSlave");
doReturn(idealState).when(mock.dataAccessor).getProperty(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
//set externalView
ExternalView externalView = mock(ExternalView.class);
// the resource sibling check will be skipped by design
when(externalView.getMinActiveReplicas()).thenReturn(-1);
doReturn(externalView).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
boolean result = InstanceValidationUtil.siblingNodesActiveReplicaCheck(mock.dataAccessor, TEST_INSTANCE);
Assert.assertTrue(result);
}
@Test(expectedExceptions = HelixException.class)
public void TestSiblingNodesActiveReplicaCheck_exception_whenExternalViewUnavailable() {
String resource = "resource";
Mock mock = new Mock();
doReturn(ImmutableList.of(resource)).when(mock.dataAccessor)
.getChildNames(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
// set ideal state
IdealState idealState = mock(IdealState.class);
when(idealState.isEnabled()).thenReturn(true);
when(idealState.isValid()).thenReturn(true);
when(idealState.getStateModelDefRef()).thenReturn("MasterSlave");
doReturn(idealState).when(mock.dataAccessor).getProperty(argThat(new PropertyKeyArgument(PropertyType.IDEALSTATES)));
doReturn(null).when(mock.dataAccessor)
.getProperty(argThat(new PropertyKeyArgument(PropertyType.EXTERNALVIEW)));
InstanceValidationUtil.siblingNodesActiveReplicaCheck(mock.dataAccessor, TEST_INSTANCE);
}
private class Mock {
HelixDataAccessor dataAccessor;
ConfigAccessor configAccessor;
Mock() {
this.dataAccessor = mock(HelixDataAccessor.class);
this.configAccessor = mock(ConfigAccessor.class);
when(dataAccessor.keyBuilder()).thenReturn(BUILDER);
}
}
public static class PropertyKeyArgument implements ArgumentMatcher<PropertyKey> {
private PropertyType propertyType;
public PropertyKeyArgument(PropertyType propertyType) {
this.propertyType = propertyType;
}
@Override
public boolean matches(PropertyKey propertyKey) {
return this.propertyType == propertyKey.getType();
}
}
}
| 9,443 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/util/TestRebalanceScheduler.java
|
package org.apache.helix.util;
/*
* 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 org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.util.RebalanceScheduler;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.MasterSlaveSMD;
import org.apache.helix.model.ResourceConfig;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestRebalanceScheduler extends ZkTestBase {
private final String CLASS_NAME = getShortClassName();
private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
private HelixManager _manager;
private ConfigAccessor _configAccessor;
private final int NUM_ATTEMPTS = 10;
@BeforeClass
public void beforeClass() throws Exception {
_gSetupTool.addCluster(CLUSTER_NAME, true);
_manager = HelixManagerFactory
.getZKHelixManager(CLUSTER_NAME, "Test", InstanceType.ADMINISTRATOR, ZK_ADDR);
_manager.connect();
_configAccessor = new ConfigAccessor(_gZkClient);
}
@Test
public void testInvokeRebalanceAndInvokeRebalanceForResource() {
String resourceName = "ResourceToInvoke";
_gSetupTool.getClusterManagementTool()
.addResource(CLUSTER_NAME, resourceName, 5, MasterSlaveSMD.name);
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, resourceName);
// Add listfields for ResourceConfig
ResourceConfig resourceConfig = new ResourceConfig(resourceName);
resourceConfig.setPreferenceLists(Collections.singletonMap("0", Arrays.asList("1", "2", "3")));
_configAccessor.setResourceConfig(CLUSTER_NAME, resourceName, resourceConfig);
int i = 0;
while (i++ < NUM_ATTEMPTS) {
RebalanceScheduler.invokeRebalance(_manager.getHelixDataAccessor(), resourceName);
RebalanceScheduler
.invokeRebalanceForResourceConfig(_manager.getHelixDataAccessor(), resourceName);
}
IdealState newIdealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, resourceName);
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
ResourceConfig newResourceConfig =
accessor.getProperty(accessor.keyBuilder().resourceConfig(resourceName));
// Starting version should be 0 and finally the version should be same as NUM_ATTEMPTS
Assert.assertTrue(idealState.getRecord().equals(newIdealState.getRecord()));
Assert.assertEquals(idealState.getStat().getVersion(), 0);
Assert.assertEquals(newIdealState.getStat().getVersion(), NUM_ATTEMPTS);
Assert.assertTrue(resourceConfig.getRecord().equals(newResourceConfig.getRecord()));
Assert.assertEquals(
resourceConfig.getStat().getVersion(), 0);
Assert.assertEquals(newResourceConfig.getStat().getVersion(), NUM_ATTEMPTS);
}
}
| 9,444 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/participant/TestDistControllerElection.java
|
package org.apache.helix.participant;
/*
* 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.List;
import java.util.Map;
import org.apache.helix.HelixException;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixTimerTask;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.controller.GenericHelixController;
import org.apache.helix.manager.zk.DistributedLeaderElection;
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.model.LiveInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class TestDistControllerElection extends ZkUnitTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestDistControllerElection.class);
@Test()
public void testController() throws Exception {
System.out.println("START TestDistControllerElection at "
+ new Date(System.currentTimeMillis()));
String className = getShortClassName();
final String clusterName = CLUSTER_PREFIX + "_" + className + "_" + "testController";
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
TestHelper.setupEmptyCluster(_gZkClient, clusterName);
final String controllerName = "controller_0";
HelixManager manager =
new MockZKHelixManager(clusterName, controllerName, InstanceType.CONTROLLER, _gZkClient);
GenericHelixController controller0 = new GenericHelixController();
List<HelixTimerTask> timerTasks = Collections.emptyList();
DistributedLeaderElection election =
new DistributedLeaderElection(manager, controller0, timerTasks);
NotificationContext context = new NotificationContext(manager);
try {
context.setType(NotificationContext.Type.INIT);
election.onControllerChange(context);
// path = PropertyPathConfig.getPath(PropertyType.LEADER, clusterName);
// ZNRecord leaderRecord = _gZkClient.<ZNRecord> readData(path);
LiveInstance liveInstance = accessor.getProperty(keyBuilder.controllerLeader());
AssertJUnit.assertEquals(controllerName, liveInstance.getInstanceName());
// AssertJUnit.assertNotNull(election.getController());
// AssertJUnit.assertNull(election.getLeader());
} finally {
manager.disconnect();
controller0.shutdown();
}
manager =
new MockZKHelixManager(clusterName, "controller_1", InstanceType.CONTROLLER, _gZkClient);
GenericHelixController controller1 = new GenericHelixController();
election = new DistributedLeaderElection(manager, controller1, timerTasks);
context = new NotificationContext(manager);
context.setType(NotificationContext.Type.INIT);
try {
election.onControllerChange(context);
// leaderRecord = _gZkClient.<ZNRecord> readData(path);
LiveInstance liveInstance = accessor.getProperty(keyBuilder.controllerLeader());
AssertJUnit.assertEquals(controllerName, liveInstance.getInstanceName());
// AssertJUnit.assertNull(election.getController());
// AssertJUnit.assertNull(election.getLeader());
} finally {
manager.disconnect();
controller1.shutdown();
accessor.removeProperty(keyBuilder.controllerLeader());
TestHelper.dropCluster(clusterName, _gZkClient);
}
System.out.println("END TestDistControllerElection at " + new Date(System.currentTimeMillis()));
}
@Test(dependsOnMethods = "testController")
public void testControllerParticipant() throws Exception {
String className = getShortClassName();
LOG.info("RUN " + className + " at " + new Date(System.currentTimeMillis()));
final String clusterName =
CONTROLLER_CLUSTER_PREFIX + "_" + className + "_" + "testControllerParticipant";
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
TestHelper.setupEmptyCluster(_gZkClient, clusterName);
final String controllerName = "controller_0";
HelixManager manager =
new MockZKHelixManager(clusterName, controllerName, InstanceType.CONTROLLER_PARTICIPANT,
_gZkClient);
GenericHelixController controller0 = new GenericHelixController();
List<HelixTimerTask> timerTasks = Collections.emptyList();
DistributedLeaderElection election =
new DistributedLeaderElection(manager, controller0, timerTasks);
NotificationContext context = new NotificationContext(manager);
context.setType(NotificationContext.Type.CALLBACK);
try {
election.onControllerChange(context);
LiveInstance liveInstance = accessor.getProperty(keyBuilder.controllerLeader());
AssertJUnit.assertEquals(controllerName, liveInstance.getInstanceName());
// path = PropertyPathConfig.getPath(PropertyType.LEADER, clusterName);
// ZNRecord leaderRecord = _gZkClient.<ZNRecord> readData(path);
// AssertJUnit.assertEquals(controllerName, leaderRecord.getSimpleField("LEADER"));
// AssertJUnit.assertNotNull(election.getController());
// AssertJUnit.assertNotNull(election.getLeader());
}
finally {
manager.disconnect();
controller0.shutdown();
}
manager =
new MockZKHelixManager(clusterName, "controller_1", InstanceType.CONTROLLER_PARTICIPANT,
_gZkClient);
GenericHelixController controller1 = new GenericHelixController();
election = new DistributedLeaderElection(manager, controller1, timerTasks);
context = new NotificationContext(manager);
context.setType(NotificationContext.Type.CALLBACK);
try {
election.onControllerChange(context);
LiveInstance liveInstance = accessor.getProperty(keyBuilder.controllerLeader());
AssertJUnit.assertEquals(controllerName, liveInstance.getInstanceName());
// leaderRecord = _gZkClient.<ZNRecord> readData(path);
// AssertJUnit.assertEquals(controllerName, leaderRecord.getSimpleField("LEADER"));
// AssertJUnit.assertNull(election.getController());
// AssertJUnit.assertNull(election.getLeader());
} finally {
manager.disconnect();
controller1.shutdown();
}
accessor.removeProperty(keyBuilder.controllerLeader());
TestHelper.dropCluster(clusterName, _gZkClient);
LOG.info("END " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
}
@Test(dependsOnMethods = "testController")
public void testParticipant() throws Exception {
String className = getShortClassName();
LOG.info("RUN " + className + " at " + new Date(System.currentTimeMillis()));
final String clusterName = CLUSTER_PREFIX + "_" + className + "_" + "testParticipant";
TestHelper.setupEmptyCluster(_gZkClient, clusterName);
final String controllerName = "participant_0";
HelixManager manager =
new MockZKHelixManager(clusterName, controllerName, InstanceType.PARTICIPANT, _gZkClient);
GenericHelixController participant0 = new GenericHelixController();
List<HelixTimerTask> timerTasks = Collections.emptyList();
try {
DistributedLeaderElection election =
new DistributedLeaderElection(manager, participant0, timerTasks);
Assert.fail(
"Should not be able construct DistributedLeaderElection object using participant manager.");
} catch (HelixException ex) {
// expected
}
participant0.shutdown();
manager.disconnect();
TestHelper.dropCluster(clusterName, _gZkClient);
}
@Test(dependsOnMethods = "testController")
public void testCompeteLeadership() throws Exception {
final int managerCount = 3;
String className = getShortClassName();
final String clusterName = CLUSTER_PREFIX + "_" + className + "_" + "testCompeteLeadership";
final ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor(_gZkClient));
final PropertyKey.Builder keyBuilder = accessor.keyBuilder();
TestHelper.setupEmptyCluster(_gZkClient, clusterName);
// Create controller leaders
final Map<String, ZKHelixManager> managerList = new HashMap<>();
final List<GenericHelixController> controllers = new ArrayList<>();
for (int i = 0; i < managerCount; i++) {
String controllerName = "controller_" + i;
ZKHelixManager manager =
new ZKHelixManager(clusterName, controllerName, InstanceType.CONTROLLER, ZK_ADDR);
GenericHelixController controller0 = new GenericHelixController();
DistributedLeaderElection election =
new DistributedLeaderElection(manager, controller0, Collections.EMPTY_LIST);
controllers.add(controller0);
manager.connect();
managerList.put(manager.getInstanceName(), manager);
}
try {
// Remove leader manager one by one, and verify if the leader node exists
while (!managerList.isEmpty()) {
// Ensure a controller successfully acquired leadership.
Assert.assertTrue(TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
LiveInstance liveInstance = accessor.getProperty(keyBuilder.controllerLeader());
if (liveInstance != null) {
// disconnect the current leader manager
managerList.remove(liveInstance.getInstanceName()).disconnect();
return true;
} else {
return false;
}
}
}, 1000));
}
} finally {
for (GenericHelixController controller : controllers) {
controller.shutdown();
}
for (ZKHelixManager mgr: managerList.values()) {
mgr.disconnect();
}
TestHelper.dropCluster(clusterName, _gZkClient);
}
}
}
| 9,445 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/participant/TestDistControllerStateModel.java
|
package org.apache.helix.participant;
/*
* 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.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestDistControllerStateModel extends ZkUnitTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestDistControllerStateModel.class);
final String clusterName = CLUSTER_PREFIX + "_" + getShortClassName();
DistClusterControllerStateModel stateModel = null;
@BeforeMethod()
public void beforeMethod() {
stateModel = new DistClusterControllerStateModel(ZK_ADDR);
if (_gZkClient.exists("/" + clusterName)) {
_gZkClient.deleteRecursively("/" + clusterName);
}
TestHelper.setupEmptyCluster(_gZkClient, clusterName);
}
@AfterMethod
public void afterMethod() throws Exception {
if (_gZkClient.exists("/" + clusterName)) {
TestHelper.dropCluster(clusterName, _gZkClient);
}
}
@Test()
public void testOnBecomeStandbyFromOffline() {
stateModel.onBecomeStandbyFromOffline(new Message(new ZNRecord("test")), null);
}
@Test()
public void testOnBecomeLeaderFromStandby() {
Message message = new Message(MessageType.STATE_TRANSITION, "0");
message.setPartitionName(clusterName);
message.setTgtName("controller_0");
try {
stateModel.onBecomeLeaderFromStandby(message, new NotificationContext(null));
} catch (Exception e) {
LOG.error("Exception becoming leader from standby", e);
}
stateModel.onBecomeStandbyFromLeader(message, new NotificationContext(null));
}
@Test()
public void testOnBecomeStandbyFromLeader() {
Message message = new Message(MessageType.STATE_TRANSITION, "0");
message.setPartitionName(clusterName);
message.setTgtName("controller_0");
stateModel.onBecomeStandbyFromLeader(message, new NotificationContext(null));
}
@Test()
public void testOnBecomeOfflineFromStandby() {
Message message = new Message(MessageType.STATE_TRANSITION, "0");
message.setPartitionName(clusterName);
message.setTgtName("controller_0");
stateModel.onBecomeOfflineFromStandby(message, null);
}
@Test()
public void testOnBecomeDroppedFromOffline() {
stateModel.onBecomeDroppedFromOffline(null, null);
}
@Test()
public void testOnBecomeOfflineFromDropped() {
stateModel.onBecomeOfflineFromDropped(null, null);
}
@Test()
public void testRollbackOnError() {
Message message = new Message(MessageType.STATE_TRANSITION, "0");
message.setPartitionName(clusterName);
message.setTgtName("controller_0");
try {
stateModel.onBecomeLeaderFromStandby(message, new NotificationContext(null));
} catch (Exception e) {
LOG.error("Exception becoming leader from standby", e);
}
stateModel.rollbackOnError(message, new NotificationContext(null), null);
}
@Test()
public void testReset() {
Message message = new Message(MessageType.STATE_TRANSITION, "0");
message.setPartitionName(clusterName);
message.setTgtName("controller_0");
try {
stateModel.onBecomeLeaderFromStandby(message, new NotificationContext(null));
} catch (Exception e) {
LOG.error("Exception becoming leader from standby", e);
}
stateModel.reset();
}
}
| 9,446 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/participant/MockZKHelixManager.java
|
package org.apache.helix.participant;
/*
* 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.Set;
import java.util.UUID;
import org.apache.helix.ClusterMessagingService;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerProperties;
import org.apache.helix.InstanceType;
import org.apache.helix.LiveInstanceInfoProvider;
import org.apache.helix.PreConnectCallback;
import org.apache.helix.PropertyKey;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.api.listeners.ClusterConfigChangeListener;
import org.apache.helix.api.listeners.ConfigChangeListener;
import org.apache.helix.api.listeners.ControllerChangeListener;
import org.apache.helix.api.listeners.CurrentStateChangeListener;
import org.apache.helix.api.listeners.CustomizedStateChangeListener;
import org.apache.helix.api.listeners.CustomizedStateConfigChangeListener;
import org.apache.helix.api.listeners.CustomizedStateRootChangeListener;
import org.apache.helix.api.listeners.CustomizedViewChangeListener;
import org.apache.helix.api.listeners.CustomizedViewRootChangeListener;
import org.apache.helix.api.listeners.ExternalViewChangeListener;
import org.apache.helix.api.listeners.IdealStateChangeListener;
import org.apache.helix.api.listeners.InstanceConfigChangeListener;
import org.apache.helix.api.listeners.LiveInstanceChangeListener;
import org.apache.helix.api.listeners.MessageListener;
import org.apache.helix.api.listeners.ResourceConfigChangeListener;
import org.apache.helix.api.listeners.ScopedConfigChangeListener;
import org.apache.helix.controller.pipeline.Pipeline;
import org.apache.helix.healthcheck.ParticipantHealthReportCollector;
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.messaging.DefaultMessagingService;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.store.zk.ZkHelixPropertyStore;
import org.apache.helix.task.TaskConstants;
import org.testng.collections.Lists;
public class MockZKHelixManager implements HelixManager {
private final ZKHelixDataAccessor _accessor;
private final String _instanceName;
private final String _clusterName;
private final InstanceType _type;
public MockZKHelixManager(String clusterName, String instanceName, InstanceType type,
HelixZkClient zkClient) {
_instanceName = instanceName;
_clusterName = clusterName;
_type = type;
_accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor(zkClient));
}
@Override
public void connect() throws Exception {
// TODO Auto-generated method stub
}
@Override
public boolean isConnected() {
// TODO Auto-generated method stub
return false;
}
@Override
public void disconnect() {
// TODO Auto-generated method stub
}
@Override
public void addIdealStateChangeListener(IdealStateChangeListener listener) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addIdealStateChangeListener(org.apache.helix.IdealStateChangeListener listener) throws Exception {
}
@Override
public void addLiveInstanceChangeListener(LiveInstanceChangeListener listener) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void setEnabledControlPipelineTypes(Set<Pipeline.Type> types) {
}
@Override
public void addLiveInstanceChangeListener(org.apache.helix.LiveInstanceChangeListener listener) throws Exception {
}
@Override
public void addResourceConfigChangeListener(ResourceConfigChangeListener listener)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addCustomizedStateConfigChangeListener(CustomizedStateConfigChangeListener listener)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addClusterfigChangeListener(ClusterConfigChangeListener listener)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addConfigChangeListener(ConfigChangeListener listener) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addMessageListener(MessageListener listener, String instanceName) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addMessageListener(org.apache.helix.MessageListener listener, String instanceName) throws Exception {
}
@Override
public void addCurrentStateChangeListener(CurrentStateChangeListener listener,
String instanceName, String sessionId) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addCurrentStateChangeListener(org.apache.helix.CurrentStateChangeListener listener, String instanceName,
String sessionId) throws Exception {
}
@Override
public void addCustomizedStateRootChangeListener(CustomizedStateRootChangeListener listener,
String instanceName) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addCustomizedStateChangeListener(CustomizedStateChangeListener listener,
String instanceName, String customizedStateType) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addExternalViewChangeListener(ExternalViewChangeListener listener) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addCustomizedViewChangeListener(CustomizedViewChangeListener listener, String customizedStateType) throws Exception {
// TODO Auto-generated method stub
}
public void addCustomizedViewRootChangeListener(CustomizedViewRootChangeListener listener) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addTargetExternalViewChangeListener(ExternalViewChangeListener listener) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addExternalViewChangeListener(org.apache.helix.ExternalViewChangeListener listener) throws Exception {
}
@Override
public boolean removeListener(PropertyKey key, Object listener) {
// TODO Auto-generated method stub
return false;
}
@Override
public HelixDataAccessor getHelixDataAccessor() {
return _accessor;
}
@Override
public String getClusterName() {
return _clusterName;
}
@Override
public String getMetadataStoreConnectionString() {
return null;
}
@Override
public String getInstanceName() {
return _instanceName;
}
@Override
public String getSessionId() {
// TODO Auto-generated method stub
return UUID.randomUUID().toString();
}
@Override
public long getLastNotificationTime() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void addControllerListener(ControllerChangeListener listener) {
// TODO Auto-generated method stub
}
@Override
public void addControllerListener(org.apache.helix.ControllerChangeListener listener) {
}
@Override
public HelixAdmin getClusterManagmentTool() {
// TODO Auto-generated method stub
return null;
}
@Override
public ClusterMessagingService getMessagingService() {
return new DefaultMessagingService(this);
}
@Override
public InstanceType getInstanceType() {
return _type;
}
@Override
public String getVersion() {
// TODO Auto-generated method stub
return UUID.randomUUID().toString();
}
@Override
public StateMachineEngine getStateMachineEngine() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isLeader() {
// TODO Auto-generated method stub
return false;
}
@Override
public ConfigAccessor getConfigAccessor() {
// TODO Auto-generated method stub
return null;
}
@Override
public void startTimerTasks() {
// TODO Auto-generated method stub
}
@Override
public void stopTimerTasks() {
// TODO Auto-generated method stub
}
@Override
public void addPreConnectCallback(PreConnectCallback callback) {
// TODO Auto-generated method stub
}
@Override
public ZkHelixPropertyStore<ZNRecord> getHelixPropertyStore() {
// TODO Auto-generated method stub
return new ZkHelixPropertyStore<>(
(ZkBaseDataAccessor<ZNRecord>) _accessor.getBaseDataAccessor(), TaskConstants.REBALANCER_CONTEXT_ROOT, Lists.<String>newArrayList());
}
@Override
public void addInstanceConfigChangeListener(InstanceConfigChangeListener listener)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addInstanceConfigChangeListener(org.apache.helix.InstanceConfigChangeListener listener) throws Exception {
}
@Override
public void addConfigChangeListener(ScopedConfigChangeListener listener, ConfigScopeProperty scope)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void addConfigChangeListener(org.apache.helix.ScopedConfigChangeListener listener, ConfigScopeProperty scope)
throws Exception {
}
@Override
public void setLiveInstanceInfoProvider(LiveInstanceInfoProvider liveInstanceInfoProvider) {
// TODO Auto-generated method stub
}
@Override
public HelixManagerProperties getProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public void addControllerMessageListener(MessageListener listener) {
// TODO Auto-generated method stub
}
@Override
public void addControllerMessageListener(org.apache.helix.MessageListener listener) {
}
@Override
public ParticipantHealthReportCollector getHealthReportCollector() {
// TODO Auto-generated method stub
return null;
}
@Override
public Long getSessionStartTime() {
return 0L;
}
}
| 9,447 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/participant/TestDistControllerStateModelFactory.java
|
package org.apache.helix.participant;
/*
* 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.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.model.Message;
import org.testng.annotations.Test;
public class TestDistControllerStateModelFactory {
final String zkAddr = ZkUnitTestBase.ZK_ADDR;
@Test()
public void testDistControllerStateModelFactory() {
DistClusterControllerStateModelFactory factory =
new DistClusterControllerStateModelFactory(zkAddr);
DistClusterControllerStateModel stateModel = factory.createNewStateModel("name", "key");
stateModel.onBecomeStandbyFromOffline(new Message(new ZNRecord("Test")), null);
}
}
| 9,448 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/participant
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/participant/statemachine/TestStateModelParser.java
|
package org.apache.helix.participant.statemachine;
/*
* 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.reflect.Method;
import org.apache.helix.NotificationContext;
import org.apache.helix.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestStateModelParser {
private static Logger LOG = LoggerFactory.getLogger(TestStateModelParser.class);
@StateModelInfo(initialState = "OFFLINE", states = {
"MASTER", "SLAVE", "ERROR"
})
class StateModelUsingAnnotation extends StateModel {
@Transition(to = "SLAVE", from = "OFFLINE")
public void onBecomeSlaveFromOffline(Message message, NotificationContext context) {
LOG.info("Become SLAVE from OFFLINE");
}
@Override
@Transition(to = "DROPPED", from = "ERROR")
public void onBecomeDroppedFromError(Message message, NotificationContext context) {
LOG.info("Become DROPPED from ERROR");
}
}
@StateModelInfo(initialState = "OFFLINE", states = {
"MASTER", "SLAVE", "ERROR"
})
class DerivedStateModelUsingAnnotation extends StateModelUsingAnnotation {
@Transition(to = "SLAVE", from = "OFFLINE")
public void derivedOnBecomeSlaveFromOffline(Message message, NotificationContext context) {
LOG.info("Derived Become SLAVE from OFFLINE");
}
}
class StateModelUsingNameConvention extends StateModel {
// empty state model
}
@Test
public void testUsingAnnotation() {
StateModelParser parser = new StateModelParser();
StateModelUsingAnnotation testModel = new StateModelUsingAnnotation();
Method method =
parser.getMethodForTransitionUsingAnnotation(testModel.getClass(), "offline", "slave",
new Class[] {
Message.class, NotificationContext.class
});
// System.out.println("method-name: " + method.getName());
Assert.assertNotNull(method);
Assert.assertEquals(method.getName(), "onBecomeSlaveFromOffline");
}
@Test
public void testDerivedUsingAnnotation() {
StateModelParser parser = new StateModelParser();
DerivedStateModelUsingAnnotation testModel = new DerivedStateModelUsingAnnotation();
Method method =
parser.getMethodForTransitionUsingAnnotation(testModel.getClass(), "offline", "slave",
new Class[] {
Message.class, NotificationContext.class
});
// System.out.println("method-name: " + method.getName());
Assert.assertNotNull(method);
Assert.assertEquals(method.getName(), "derivedOnBecomeSlaveFromOffline");
method =
parser.getMethodForTransitionUsingAnnotation(testModel.getClass(), "error", "dropped",
new Class[] {
Message.class, NotificationContext.class
});
// System.out.println("method: " + method);
Assert.assertNotNull(method);
Assert.assertEquals(method.getName(), "onBecomeDroppedFromError");
}
@Test
public void testUsingNameConvention() {
StateModelParser parser = new StateModelParser();
StateModelUsingNameConvention testModel = new StateModelUsingNameConvention();
Method method =
parser.getMethodForTransition(testModel.getClass(), "error", "dropped", new Class[] {
Message.class, NotificationContext.class
});
Assert.assertNotNull(method);
Assert.assertEquals(method.getName(), "onBecomeDroppedFromError");
}
}
| 9,449 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestStateTransitionCancellation.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.HashMap;
import java.util.Map;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixRollbackException;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
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.mock.participant.MockDelayMSStateModel;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
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.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskFactory;
import org.apache.helix.task.TaskStateModelFactory;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestStateTransitionCancellation extends TaskTestBase {
// TODO: Replace the thread sleep with synchronized condition check
private ConfigAccessor _configAccessor;
private ZkHelixClusterVerifier _verifier;
@BeforeClass
public void beforeClass() throws Exception {
_participants = new MockParticipantManager[_numNodes];
_numDbs = 1;
_numPartitions = 20;
_numNodes = 2;
_numReplicas = 2;
_verifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
_gSetupTool.addCluster(CLUSTER_NAME, true);
setupParticipants();
setupDBs();
registerParticipants(_participants, _numNodes, _startPort, 0, -3000000L);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
createManagers();
_configAccessor = new ConfigAccessor(_gZkClient);
}
@Test
public void testCancellationWhenDisableResource() throws InterruptedException {
// Enable cancellation
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.stateTransitionCancelEnabled(true);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
// Wait for assignment done
Thread.sleep(2000);
// Disable the resource
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME,
WorkflowGenerator.DEFAULT_TGT_DB, false);
// Wait for pipeline reaching final stage
Assert.assertTrue(_verifier.verifyByPolling());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
for (String partition : externalView.getPartitionSet()) {
for (String currentState : externalView.getStateMap(partition).values()) {
Assert.assertEquals(currentState, "OFFLINE");
}
}
}
@Test
public void testDisableCancellationWhenDisableResource() throws InterruptedException {
// Disable cancellation
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.stateTransitionCancelEnabled(false);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
// Reenable resource
stateCleanUp();
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME,
WorkflowGenerator.DEFAULT_TGT_DB, true);
// Wait for assignment done
Thread.sleep(2000);
// Disable the resource
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME,
WorkflowGenerator.DEFAULT_TGT_DB, false);
// Wait for pipeline reaching final stage
Thread.sleep(2000L);
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
for (String partition : externalView.getPartitionSet()) {
Assert.assertTrue(externalView.getStateMap(partition).values().contains("SLAVE"));
}
}
@Test
public void testRebalancingCauseCancellation() throws InterruptedException {
// Enable cancellation
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.stateTransitionCancelEnabled(true);
clusterConfig.setPersistBestPossibleAssignment(true);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
// Reenable resource
stateCleanUp();
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME,
WorkflowGenerator.DEFAULT_TGT_DB, true);
// Wait for assignment done
Thread.sleep(2000);
int numNodesToStart = 10;
for (int i = 0; i < numNodesToStart; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (_startPort + _numNodes + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
MockParticipantManager[] newParticipants = new MockParticipantManager[numNodesToStart];
registerParticipants(newParticipants, numNodesToStart, _startPort + _numNodes, 1000, -3000000L);
// Wait for pipeline reaching final stage
Thread.sleep(2000L);
int numOfMasters = 0;
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
for (String partition : externalView.getPartitionSet()) {
if (externalView.getStateMap(partition).values().contains("MASTER")) {
numOfMasters++;
}
}
for (MockParticipantManager participant : newParticipants) {
participant.syncStop();
}
// Either partial of state transitions have been cancelled or all the Slave -> Master
// reassigned to other cluster
Assert.assertTrue((numOfMasters > 0 && numOfMasters <= _numPartitions));
}
private void stateCleanUp() {
InternalMockDelayMSStateModel._cancelledFirstTime = true;
InternalMockDelayMSStateModel._cancelledStatic = false;
}
@StateModelInfo(initialState = "OFFLINE", states = {
"MASTER", "SLAVE", "ERROR"
})
public static class InternalMockDelayMSStateModel extends StateModel {
private static Logger LOG = LoggerFactory.getLogger(MockDelayMSStateModel.class);
private long _delay;
public static boolean _cancelledStatic;
public static boolean _cancelledFirstTime;
public InternalMockDelayMSStateModel(long delay) {
_delay = delay;
_cancelledStatic = false;
_cancelledFirstTime = true;
}
@Transition(to = "SLAVE", from = "OFFLINE")
public void onBecomeSlaveFromOffline(Message message, NotificationContext context) {
if (_delay > 0) {
try {
Thread.sleep(_delay);
} catch (InterruptedException e) {
LOG.error("Failed to sleep for " + _delay);
}
}
LOG.info("Become SLAVE from OFFLINE");
}
@Transition(to = "MASTER", from = "SLAVE")
public void onBecomeMasterFromSlave(Message message, NotificationContext context)
throws InterruptedException, HelixRollbackException {
if (_cancelledFirstTime && _delay < 0) {
while (!_cancelledStatic) {
Thread.sleep(Math.abs(1000L));
}
_cancelledFirstTime = false;
throw new HelixRollbackException("EX");
}
LOG.error("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) {
LOG.info("Become OFFLINE from SLAVE");
}
@Transition(to = "DROPPED", from = "OFFLINE")
public void onBecomeDroppedFromOffline(Message message, NotificationContext context) {
LOG.info("Become DROPPED FROM OFFLINE");
}
@Override
public void cancel() {
_cancelledStatic = true;
}
@Override
public boolean isCancelled() {
return _cancelledStatic;
}
}
public class InMockDelayMSStateModelFactory
extends StateModelFactory<InternalMockDelayMSStateModel> {
private long _delay;
@Override
public InternalMockDelayMSStateModel createNewStateModel(String resourceName,
String partitionKey) {
InternalMockDelayMSStateModel model = new InternalMockDelayMSStateModel(_delay);
return model;
}
public InMockDelayMSStateModelFactory setDelay(long delay) {
_delay = delay;
return this;
}
}
private void registerParticipants(MockParticipantManager[] participants, int numNodes,
int startPort, long sleepTime, long delay) throws InterruptedException {
Map<String, TaskFactory> taskFactoryReg = new HashMap<String, TaskFactory>();
taskFactoryReg.put(MockTask.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new MockTask(context);
}
});
for (int i = 0; i < numNodes; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (startPort + i);
participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
// add a state model with non-OFFLINE initial state
StateMachineEngine stateMach = participants[i].getStateMachineEngine();
stateMach.registerStateModelFactory("Task",
new TaskStateModelFactory(participants[i], taskFactoryReg));
InMockDelayMSStateModelFactory delayFactory =
new InMockDelayMSStateModelFactory().setDelay(delay);
stateMach.registerStateModelFactory(MASTER_SLAVE_STATE_MODEL, delayFactory);
participants[i].syncStart();
if (sleepTime > 0) {
Thread.sleep(sleepTime);
}
}
}
}
| 9,450 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestHelixUsingDifferentParams.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.common.ZkTestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
public class TestHelixUsingDifferentParams extends ZkTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestHelixUsingDifferentParams.class);
@Test()
public void testCMUsingDifferentParams() throws Exception {
System.out
.println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
int[] numResourceArray = new int[] {
1
};
int[] numPartitionsPerResourceArray = new int[] {
10
};
int[] numInstances = new int[] {
5
};
int[] replicas = new int[] {
2
};
for (int numResources : numResourceArray) {
for (int numPartitionsPerResource : numPartitionsPerResourceArray) {
for (int numInstance : numInstances) {
for (int replica : replicas) {
String uniqClusterName = "TestDiffParam_" + "rg" + numResources + "_p"
+ numPartitionsPerResource + "_n" + numInstance + "_r" + replica;
System.out.println(
"START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
TestDriver.setupCluster(uniqClusterName, ZK_ADDR, numResources,
numPartitionsPerResource, numInstance, replica);
for (int i = 0; i < numInstance; i++) {
TestDriver.startDummyParticipant(uniqClusterName, i);
}
TestDriver.startController(uniqClusterName);
TestDriver.verifyCluster(uniqClusterName, 1000, 50 * 1000);
TestDriver.stopCluster(uniqClusterName);
deleteCluster(uniqClusterName);
System.out
.println("END " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
}
}
}
}
System.out
.println("END " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,451 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestSessionExpiryInTransition.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.concurrent.atomic.AtomicBoolean;
import org.apache.helix.NotificationContext;
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.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestSessionExpiryInTransition extends ZkTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestSessionExpiryInTransition.class);
public class SessionExpiryTransition extends MockTransition {
private final AtomicBoolean _done = new AtomicBoolean();
@Override
public void doTransition(Message message, NotificationContext context) {
MockParticipantManager manager = (MockParticipantManager) context.getManager();
String instance = message.getTgtName();
String partition = message.getPartitionName();
if (instance.equals("localhost_12918") && partition.equals("TestDB0_1") // TestDB0_1 is SLAVE
// on localhost_12918
&& !_done.getAndSet(true)) {
try {
ZkTestHelper.expireSession(manager.getZkClient());
} catch (Exception e) {
LOG.error("Exception expire zk-session", e);
}
}
}
}
@Test
public void testSessionExpiryInTransition() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
final String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
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
// start controller
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].setTransition(new SessionExpiryTransition());
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,452 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestAddNodeAfterControllerStart.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 org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyPathBuilder;
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.ClusterDistributedController;
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.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestAddNodeAfterControllerStart extends ZkTestBase {
final String className = getShortClassName();
@Test
public void testStandalone() throws Exception {
String clusterName = className + "_standalone";
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
final int nodeNr = 5;
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 20, nodeNr - 1,
3, "MasterSlave", true);
MockParticipantManager[] participants = new MockParticipantManager[nodeNr];
for (int i = 0; i < nodeNr - 1; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
boolean result;
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
String msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12918");
result = checkHandlers(controller.getHandlers(), msgPath);
Assert.assertTrue(result);
_gSetupTool.addInstanceToCluster(clusterName, "localhost_12922");
_gSetupTool.rebalanceStorageCluster(clusterName, "TestDB0", 3);
participants[nodeNr - 1] = new MockParticipantManager(ZK_ADDR, clusterName, "localhost_12922");
new Thread(participants[nodeNr - 1]).start();
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12922");
result = checkHandlers(controller.getHandlers(), msgPath);
Assert.assertTrue(result);
// clean up
controller.syncStop();
for (int i = 0; i < nodeNr; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDistributed() throws Exception {
String clusterName = className + "_distributed";
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
// setup grand cluster
final String grandClusterName = "GRAND_" + clusterName;
TestHelper.setupCluster(grandClusterName, ZK_ADDR, 0, "controller", null, 0, 0, 1, 0, null,
true);
ClusterDistributedController distController =
new ClusterDistributedController(ZK_ADDR, grandClusterName, "controller_0");
distController.syncStart();
// setup cluster
_gSetupTool.addCluster(clusterName, true);
_gSetupTool.activateCluster(clusterName, "GRAND_" + clusterName, true); // addCluster2
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(grandClusterName)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// add node/resource, and do rebalance
final int nodeNr = 2;
for (int i = 0; i < nodeNr - 1; i++) {
int port = 12918 + i;
_gSetupTool.addInstanceToCluster(clusterName, "localhost_" + port);
}
_gSetupTool.addResourceToCluster(clusterName, "TestDB0", 1, "LeaderStandby");
_gSetupTool.rebalanceStorageCluster(clusterName, "TestDB0", 1);
BestPossibleExternalViewVerifier verifier2 =
new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier2.verifyByPolling());
MockParticipantManager[] participants = new MockParticipantManager[nodeNr];
for (int i = 0; i < nodeNr - 1; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
// Make sure new participants are connected
boolean result = TestHelper.verify(() -> {
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < nodeNr - 1; i++) {
if (!participants[i].isConnected()
|| !liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
Assert.assertTrue(verifier2.verifyByPolling());
// check if controller_0 has message listener for localhost_12918
String msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12918");
int numberOfListeners = ZkTestHelper.numberOfListeners(ZK_ADDR, msgPath);
// System.out.println("numberOfListeners(" + msgPath + "): " + numberOfListeners);
Assert.assertEquals(numberOfListeners, 2); // 1 of participant, and 1 of controller
_gSetupTool.addInstanceToCluster(clusterName, "localhost_12919");
_gSetupTool.rebalanceStorageCluster(clusterName, "TestDB0", 2);
participants[nodeNr - 1] = new MockParticipantManager(ZK_ADDR, clusterName, "localhost_12919");
participants[nodeNr - 1].syncStart();
Assert.assertTrue(verifier2.verifyByPolling());
// check if controller_0 has message listener for localhost_12919
msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12919");
numberOfListeners = ZkTestHelper.numberOfListeners(ZK_ADDR, msgPath);
// System.out.println("numberOfListeners(" + msgPath + "): " + numberOfListeners);
Assert.assertEquals(numberOfListeners, 2); // 1 of participant, and 1 of controller
// clean up
distController.syncStop();
for (int i = 0; i < nodeNr; i++) {
participants[i].syncStop();
}
// Check that things have been cleaned up
result = TestHelper.verify(() -> {
if (distController.isConnected()
|| accessor.getPropertyStat(accessor.keyBuilder().controllerLeader()) != null) {
return false;
}
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < nodeNr - 1; i++) {
if (participants[i].isConnected()
|| liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
deleteCluster(clusterName);
deleteCluster(grandClusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
private boolean checkHandlers(List<CallbackHandler> handlers, String path) {
for (CallbackHandler handler : handlers) {
if (handler.getPath().equals(path)) {
return true;
}
}
return false;
}
}
| 9,453 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestErrorReplicaPersist.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.ConfigAccessor;
import org.apache.helix.HelixRollbackException;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
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.rebalancer.TestAutoRebalance;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.MasterSlaveSMD;
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.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier;
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 TestErrorReplicaPersist extends ZkStandAloneCMTestBase {
@BeforeClass
public void beforeClass() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
int numNode = NODE_NR + 1;
_participants = new MockParticipantManager[numNode];
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
createResourceWithDelayedRebalance(CLUSTER_NAME, TEST_DB, MasterSlaveSMD.name, _PARTITIONS,
_replica, _replica - 1, 1800000, CrushEdRebalanceStrategy.class.getName());
for (int i = 0; i < numNode; 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 < numNode; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
participant.syncStart();
_participants[i] = participant;
}
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true, 1800000);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
boolean result = ClusterStateVerifier.verifyByZkCallback(
new TestAutoRebalance.ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
Assert.assertTrue(result);
}
@AfterClass
public void afterClass() throws Exception {
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
super.afterClass();
}
@Test
public void testErrorReplicaPersist() throws InterruptedException {
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setErrorPartitionThresholdForLoadBalance(100000);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
for (int i = 0; i < (NODE_NR + 1) / 2; i++) {
_participants[i].syncStop();
Thread.sleep(2000);
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
StateMachineEngine stateMachineEngine = participant.getStateMachineEngine();
stateMachineEngine
.registerStateModelFactory(MasterSlaveSMD.name, new MockFailedMSStateModelFactory());
participant.syncStart();
_participants[i] = participant;
}
HelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(((BestPossibleExternalViewVerifier) verifier).verifyByPolling());
for (int i = 0; i < (NODE_NR + 1) / 2; i++) {
_gSetupTool.getClusterManagementTool()
.enableInstance(CLUSTER_NAME, _participants[i].getInstanceName(), false);
}
Assert.assertTrue(((BestPossibleExternalViewVerifier) verifier).verifyByPolling());
}
class MockFailedMSStateModelFactory
extends StateModelFactory<MockFailedMSStateModel> {
@Override
public MockFailedMSStateModel createNewStateModel(String resourceName,
String partitionKey) {
MockFailedMSStateModel model = new MockFailedMSStateModel();
return model;
}
}
@StateModelInfo(initialState = "OFFLINE", states = { "MASTER", "SLAVE", "ERROR"
})
public static class MockFailedMSStateModel extends StateModel {
private static Logger LOG = LoggerFactory.getLogger(MockFailedMSStateModel.class);
public MockFailedMSStateModel() {
}
@Transition(to = "SLAVE", from = "OFFLINE") public void onBecomeSlaveFromOffline(
Message message, NotificationContext context) throws IllegalAccessException {
throw new IllegalAccessException("Failed!");
}
@Transition(to = "MASTER", from = "SLAVE") public void onBecomeMasterFromSlave(Message message,
NotificationContext context) throws InterruptedException, HelixRollbackException {
LOG.error("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) {
LOG.info("Become OFFLINE from SLAVE");
}
@Transition(to = "DROPPED", from = "OFFLINE") public void onBecomeDroppedFromOffline(
Message message, NotificationContext context) {
LOG.info("Become DROPPED FROM OFFLINE");
}
}
}
| 9,454 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDisable.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 org.apache.helix.PropertyKey.Builder;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkTestHelper;
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.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
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 TestDisable extends ZkTestBase {
@Test
public void testDisableNodeCustomIS() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 5;
String disableNode = "localhost_12918";
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
// set ideal state to customized mode
ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
Builder keyBuilder = accessor.keyBuilder();
IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
idealState.setRebalanceMode(RebalanceMode.CUSTOMIZED);
accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
// 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 _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// disable localhost_12918
String command =
"--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " false";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure localhost_12918 is in OFFLINE state
Map<String, Map<String, String>> expectStateMap = new HashMap<>();
Map<String, String> expectInstanceStateMap = new HashMap<>();
expectInstanceStateMap.put(disableNode, "OFFLINE");
expectStateMap.put(".*", expectInstanceStateMap);
boolean result =
ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
Assert.assertTrue(result, disableNode + " should be in OFFLINE");
// re-enable localhost_12918
command =
"--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " true";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure localhost_12918 is NOT in OFFLINE state
result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
Assert.assertTrue(result, disableNode + " should NOT be in OFFLINE");
// clean up
// wait for all zk callbacks done
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDisableNodeAutoIS() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 5;
String disableNode = "localhost_12919";
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 _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// disable localhost_12919
String command =
"--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " false";
ClusterSetup.processCommandLineArgs(command.split(" "));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure localhost_12919 is in OFFLINE state
Map<String, Map<String, String>> expectStateMap = new HashMap<>();
Map<String, String> expectInstanceStateMap = new HashMap<>();
expectInstanceStateMap.put(disableNode, "OFFLINE");
expectStateMap.put(".*", expectInstanceStateMap);
boolean result =
ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
Assert.assertTrue(result, disableNode + " should be in OFFLINE");
// re-enable localhost_12919
command =
"--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " true";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
result = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// make sure localhost_12919 is NOT in OFFLINE state
result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
Assert.assertTrue(result, disableNode + " should NOT be in OFFLINE");
// clean up
// wait for all zk callbacks done
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDisablePartitionCustomIS() 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
// set ideal state to customized mode
ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
Builder keyBuilder = accessor.keyBuilder();
IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
idealState.setRebalanceMode(RebalanceMode.CUSTOMIZED);
accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
// 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 _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// disable [TestDB0_0, TestDB0_5] on localhost_12919
String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
+ " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure localhost_12918 is in OFFLINE state for [TestDB0_0, TestDB0_5]
Map<String, Map<String, String>> expectStateMap = new HashMap<>();
Map<String, String> expectInstanceStateMap = new HashMap<>();
expectInstanceStateMap.put("localhost_12919", "OFFLINE");
expectStateMap.put("TestDB0_0", expectInstanceStateMap);
expectStateMap.put("TestDB0_5", expectInstanceStateMap);
boolean result =
ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
Assert.assertTrue(result,
"localhost_12919" + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");
// re-enable localhost_12919 for [TestDB0_0, TestDB0_5]
command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
+ " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
result = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// make sure localhost_12919 is NOT in OFFLINE state for [TestDB0_0, TestDB0_5]
result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
Assert.assertTrue(result, "localhost_12919" + " should NOT be in OFFLINE");
// clean up
// wait for all zk callbacks done
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDisablePartitionAutoIS() 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 _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// disable [TestDB0_0, TestDB0_5] on localhost_12919
String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
+ " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure localhost_12918 is in OFFLINE state for [TestDB0_0, TestDB0_5]
Map<String, Map<String, String>> expectStateMap = new HashMap<>();
Map<String, String> expectInstanceStateMap = new HashMap<>();
expectInstanceStateMap.put("localhost_12919", "OFFLINE");
expectStateMap.put("TestDB0_0", expectInstanceStateMap);
expectStateMap.put("TestDB0_5", expectInstanceStateMap);
boolean result =
ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
Assert.assertTrue(result,
"localhost_12919" + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");
// re-enable localhost_12919 for [TestDB0_0, TestDB0_5]
command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
+ " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure localhost_12919 is NOT in OFFLINE state for [TestDB0_0, TestDB0_5]
result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
Assert.assertTrue(result, "localhost_12919" + " should NOT be in OFFLINE");
// clean up
// wait for all zk callbacks done
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,455 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestNoThrottleDisabledPartitions.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.TestHelper;
import org.apache.helix.api.config.StateTransitionThrottleConfig;
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.ClusterConfig;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.builder.FullAutoModeISBuilder;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestNoThrottleDisabledPartitions extends ZkTestBase {
private String _resourceName = "TestDB";
private String _clusterName = getShortClassName();
private HelixDataAccessor _accessor;
private MockParticipantManager[] _participants;
/**
* Given the following setup for a partition:
* instance 1 : M
* instance 2 : S
* instance 3 : S
* and no throttle config set for recovery balance
* and throttle config of 1 set for load balance,
* test that disabling instance 1 puts this partition in recovery balance, so that all transitions
* for a partition go through.
* * instance 1 : S (M->S->Offline)
* * instance 2 : M (S->M because it's in recovery)
* * instance 3 : S
* @throws Exception
*/
@Test
public void testDisablingTopStateReplicaByDisablingInstance() throws Exception {
int participantCount = 5;
setupEnvironment(participantCount);
// Set the throttling only for load balance
setThrottleConfigForLoadBalance(1);
// Disable instance 0 so that it will cause a partition to do a load balance
PropertyKey key = _accessor.keyBuilder().instanceConfig(_participants[0].getInstanceName());
InstanceConfig instanceConfig = _accessor.getProperty(key);
instanceConfig.setInstanceEnabled(false);
_accessor.setProperty(key, instanceConfig);
// Resume the controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
Thread.sleep(500L);
// The disabled instance should not hold any top state replicas (MASTER)
PropertyKey liveInstanceKey =
_accessor.keyBuilder().liveInstance(_participants[0].getInstanceName());
LiveInstance liveInstance = _accessor.getProperty(liveInstanceKey);
if (liveInstance != null) {
String sessionId = liveInstance.getEphemeralOwner();
List<CurrentState> currentStates = _accessor.getChildValues(
_accessor.keyBuilder().currentStates(_participants[0].getInstanceName(), sessionId),
true);
for (CurrentState currentState : currentStates) {
for (Map.Entry<String, String> partitionState : currentState.getPartitionStateMap()
.entrySet()) {
Assert.assertFalse(partitionState.getValue().equals("MASTER"));
}
}
}
// clean up the cluster
controller.syncStop();
for (int i = 0; i < participantCount; i++) {
_participants[i].syncStop();
}
deleteCluster(_clusterName);
}
/**
* Given the following setup for a partition:
* instance 1 : M
* instance 2 : S
* instance 3 : S
* and no throttle config set for recovery balance
* and throttle config of 1 set for load balance,
* Instead of disabling the instance, we disable the partition in the instance config.
* * instance 1 : S (M->S->Offline)
* * instance 2 : M (S->M because it's in recovery)
* * instance 3 : S
* @throws Exception
*/
@Test
public void testDisablingPartitionOnInstance() throws Exception {
int participantCount = 5;
setupEnvironment(participantCount);
// Set the throttling only for load balance
setThrottleConfigForLoadBalance();
// In this setup, TestDB0_2 has a MASTER replica on localhost_12918
disablePartitionOnInstance(_participants[0], _resourceName + "0", "TestDB0_2");
// Resume the controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
Thread.sleep(500L);
// The disabled instance should not hold any top state replicas (MASTER)
PropertyKey liveInstanceKey =
_accessor.keyBuilder().liveInstance(_participants[0].getInstanceName());
LiveInstance liveInstance = _accessor.getProperty(liveInstanceKey);
if (liveInstance != null) {
String sessionId = liveInstance.getEphemeralOwner();
List<CurrentState> currentStates = _accessor.getChildValues(
_accessor.keyBuilder().currentStates(_participants[0].getInstanceName(), sessionId),
true);
for (CurrentState currentState : currentStates) {
for (Map.Entry<String, String> partitionState : currentState.getPartitionStateMap()
.entrySet()) {
if (partitionState.getKey().equals("TestDB0_2")) {
Assert.assertFalse(partitionState.getValue().equals("MASTER"));
}
}
}
}
// clean up the cluster
controller.syncStop();
for (int i = 0; i < participantCount; i++) {
_participants[i].syncStop();
}
deleteCluster(_clusterName);
}
/**
* Given the following setup for a partition:
* instance 1 : M
* instance 2 : S
* instance 3 : S
* and no throttle config set for recovery balance
* and throttle config of 1 set for load balance,
* Instead of disabling the instance, we disable the partition in the instance config.
* Here, we set the recovery balance config to 0. But we should still see the downward transition
* regardless.
* * instance 1 : S (M->S->Offline)
* * instance 2 : M (S->M because it's in recovery)
* * instance 3 : S
* @throws Exception
*/
@Test
public void testDisablingPartitionOnInstanceWithRecoveryThrottle() throws Exception {
int participantCount = 5;
setupEnvironment(participantCount);
// Set the throttling
setThrottleConfigForLoadBalance();
setThrottleConfigForRecoveryBalance();
// In this setup, TestDB0_2 has a MASTER replica on localhost_12918
disablePartitionOnInstance(_participants[0], _resourceName + "0", "TestDB0_2");
// Resume the controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
Thread.sleep(500L);
// The disabled instance should not hold any top state replicas (MASTER)
PropertyKey liveInstanceKey =
_accessor.keyBuilder().liveInstance(_participants[0].getInstanceName());
LiveInstance liveInstance = _accessor.getProperty(liveInstanceKey);
if (liveInstance != null) {
String sessionId = liveInstance.getEphemeralOwner();
List<CurrentState> currentStates = _accessor.getChildValues(
_accessor.keyBuilder().currentStates(_participants[0].getInstanceName(), sessionId),
true);
for (CurrentState currentState : currentStates) {
for (Map.Entry<String, String> partitionState : currentState.getPartitionStateMap()
.entrySet()) {
if (partitionState.getKey().equals("TestDB0_2")) {
Assert.assertFalse(partitionState.getValue().equals("MASTER"));
}
}
}
}
// clean up the cluster
controller.syncStop();
for (int i = 0; i < participantCount; i++) {
_participants[i].syncStop();
}
deleteCluster(_clusterName);
}
@Test
public void testNoThrottleOnDisabledInstance() throws Exception {
int participantCount = 5;
setupEnvironment(participantCount);
setThrottleConfig();
// Disable an instance so that it will not be subject to throttling
PropertyKey key = _accessor.keyBuilder().instanceConfig(_participants[0].getInstanceName());
InstanceConfig instanceConfig = _accessor.getProperty(key);
instanceConfig.setInstanceEnabled(false);
_accessor.setProperty(key, instanceConfig);
// Set the state transition delay so that transitions would be processed slowly
DelayedTransitionBase.setDelay(1000000L);
// Resume the controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
Thread.sleep(500L);
// Check that there are more messages on this Participant despite the throttle config set at 1
Assert.assertTrue(verifyMultipleMessages(_participants[0]));
// clean up the cluster
controller.syncStop();
for (int i = 0; i < participantCount; i++) {
_participants[i].syncStop();
}
deleteCluster(_clusterName);
}
@Test
public void testNoThrottleOnDisabledPartition() throws Exception {
int participantCount = 3;
setupEnvironment(participantCount);
setThrottleConfig(3); // Convert partition to replica mapping should be 1 -> 3
// Disable a partition so that it will not be subject to throttling
String partitionName = _resourceName + "0_0";
for (int i = 0; i < participantCount; i++) {
disablePartitionOnInstance(_participants[i], _resourceName + "0", partitionName);
}
String newResource = "abc";
IdealState idealState = new FullAutoModeISBuilder(newResource).setStateModel("MasterSlave")
.setStateModelFactoryName("DEFAULT").setNumPartitions(5).setNumReplica(3)
.setMinActiveReplica(2).setRebalancerMode(IdealState.RebalanceMode.FULL_AUTO)
.setRebalancerClass("org.apache.helix.controller.rebalancer.DelayedAutoRebalancer")
.setRebalanceStrategy(
"org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy")
.build();
_gSetupTool.addResourceToCluster(_clusterName, newResource, idealState);
_gSetupTool.rebalanceStorageCluster(_clusterName, newResource, 3);
// Set the state transition delay so that transitions would be processed slowly
DelayedTransitionBase.setDelay(1000000L);
// Now Helix will try to bring this up on all instances. But the disabled partition will go to
// offline. This should allow each instance to have 2 messages despite having the throttle set
// at 1
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
Thread.sleep(500L);
// The throttle quota will be consumed by first partition with all
for (MockParticipantManager participantManager : _participants) {
Assert.assertTrue(verifySingleMessage(participantManager));
}
// clean up the cluster
controller.syncStop();
for (int i = 0; i < participantCount; i++) {
_participants[i].syncStop();
}
deleteCluster(_clusterName);
}
/**
* Set up the cluster and pause the controller.
* @param participantCount
* @throws Exception
*/
private void setupEnvironment(int participantCount) throws Exception {
_participants = new MockParticipantManager[participantCount];
_accessor = new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
setupCluster(_clusterName, participantCount);
DelayedTransitionBase transition = new DelayedTransitionBase(10L);
// Start _participants
for (int i = 0; i < participantCount; i++) {
_participants[i] =
new MockParticipantManager(ZK_ADDR, _clusterName, "localhost_" + (12918 + i));
_participants[i].setTransition(transition);
_participants[i].syncStart();
}
// Start the controller and verify that it is in the best possible state
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();
Assert.assertTrue(verifier.verify(3000));
// Pause the controller
controller.syncStop();
}
private void setThrottleConfig() {
setThrottleConfig(1);
}
/**
* Set all throttle configs at 1 so that we could test by observing the number of ongoing
* transitions.
*/
private void setThrottleConfig(int maxReplicas) {
PropertyKey.Builder keyBuilder = _accessor.keyBuilder();
ClusterConfig clusterConfig = _accessor.getProperty(_accessor.keyBuilder().clusterConfig());
clusterConfig.setResourcePriorityField("Name");
List<StateTransitionThrottleConfig> throttleConfigs = new ArrayList<>();
// Add throttling at cluster-level
throttleConfigs.add(new StateTransitionThrottleConfig(
StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, maxReplicas));
throttleConfigs.add(
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, maxReplicas));
throttleConfigs
.add(new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.ANY,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, maxReplicas));
// Add throttling at instance level
throttleConfigs
.add(new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.ANY,
StateTransitionThrottleConfig.ThrottleScope.INSTANCE, maxReplicas));
clusterConfig.setStateTransitionThrottleConfigs(throttleConfigs);
_accessor.setProperty(keyBuilder.clusterConfig(), clusterConfig);
}
private void setThrottleConfigForLoadBalance() {
setThrottleConfigForLoadBalance(0);
}
/**
* Set throttle limits only for load balance so that none of them would happen.
*/
private void setThrottleConfigForLoadBalance(int maxReplicas) {
PropertyKey.Builder keyBuilder = _accessor.keyBuilder();
ClusterConfig clusterConfig = _accessor.getProperty(_accessor.keyBuilder().clusterConfig());
clusterConfig.setResourcePriorityField("Name");
List<StateTransitionThrottleConfig> throttleConfigs = new ArrayList<>();
// Add throttling at cluster-level
throttleConfigs.add(
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, maxReplicas));
// Add throttling at instance level
throttleConfigs.add(
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.INSTANCE, maxReplicas));
clusterConfig.setStateTransitionThrottleConfigs(throttleConfigs);
_accessor.setProperty(keyBuilder.clusterConfig(), clusterConfig);
}
/**
* Set throttle limits only for recovery balance so that none of them would happen.
*/
private void setThrottleConfigForRecoveryBalance() {
PropertyKey.Builder keyBuilder = _accessor.keyBuilder();
ClusterConfig clusterConfig = _accessor.getProperty(_accessor.keyBuilder().clusterConfig());
clusterConfig.setResourcePriorityField("Name");
List<StateTransitionThrottleConfig> throttleConfigs = new ArrayList<>();
// Add throttling at cluster-level
throttleConfigs.add(new StateTransitionThrottleConfig(
StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 0));
// Add throttling at instance level
throttleConfigs.add(new StateTransitionThrottleConfig(
StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.INSTANCE, 0));
clusterConfig.setStateTransitionThrottleConfigs(throttleConfigs);
_accessor.setProperty(keyBuilder.clusterConfig(), clusterConfig);
}
/**
* Set up delayed rebalancer and minimum active replica settings to mimic user's use case.
* @param clusterName
* @param participantCount
* @throws Exception
*/
private void setupCluster(String clusterName, int participantCount) throws Exception {
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant start port
"localhost", // participant name prefix
_resourceName, // resource name prefix
3, // resources
5, // partitions per resource
participantCount, // number of nodes
3, // replicas
"MasterSlave", IdealState.RebalanceMode.FULL_AUTO, true); // do rebalance
// Enable DelayedAutoRebalance
ClusterConfig clusterConfig = _accessor.getProperty(_accessor.keyBuilder().clusterConfig());
clusterConfig.setDelayRebalaceEnabled(true);
clusterConfig.setRebalanceDelayTime(1800000L);
_accessor.setProperty(_accessor.keyBuilder().clusterConfig(), clusterConfig);
// Set minActiveReplicas at 2
List<String> idealStates = _accessor.getChildNames(_accessor.keyBuilder().idealStates());
for (String is : idealStates) {
IdealState idealState = _accessor.getProperty(_accessor.keyBuilder().idealStates(is));
idealState.setMinActiveReplicas(2);
idealState.setRebalanceStrategy(
"org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy");
idealState
.setRebalancerClassName("org.apache.helix.controller.rebalancer.DelayedAutoRebalancer");
_accessor.setProperty(_accessor.keyBuilder().idealStates(is), idealState);
}
}
/**
* Disable select partitions from the first instance to test that these partitions are not subject
* to throttling.
*/
private void disablePartitionOnInstance(MockParticipantManager participant, String resourceName,
String partitionName) {
String instanceName = participant.getInstanceName();
PropertyKey key = _accessor.keyBuilder().instanceConfig(instanceName);
InstanceConfig instanceConfig = _accessor.getProperty(key);
instanceConfig.setInstanceEnabledForPartition(resourceName, partitionName, false);
_accessor.setProperty(key, instanceConfig);
}
/**
* Ensure that there are more than 1 message for a given Participant.
* @param participant
* @return
*/
private boolean verifyMultipleMessages(final MockParticipantManager participant) {
PropertyKey key = _accessor.keyBuilder().messages(participant.getInstanceName());
List<String> messageNames = _accessor.getChildNames(key);
if (messageNames != null) {
return messageNames.size() > 1;
}
return false;
}
/**
* Ensure that there are 1 messages for a given Participant.
* @param participant
* @return
*/
private boolean verifySingleMessage(final MockParticipantManager participant) {
PropertyKey key = _accessor.keyBuilder().messages(participant.getInstanceName());
List<String> messageNames = _accessor.getChildNames(key);
if (messageNames != null) {
return messageNames.size() == 1;
}
return false;
}
}
| 9,456 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestResetResource.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 TestResetResource extends ZkTestBase {
@Test
public void testResetNode() 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 resource "TestDB0"
participants[0].setTransition(null);
String command = "--zkSvr " + ZK_ADDR + " --resetResource " + clusterName + " TestDB0";
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,457 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestAddStateModelFactoryAfterConnect.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 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.mock.participant.MockMSModelFactory;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
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;
public class TestAddStateModelFactoryAfterConnect extends ZkTestBase {
@Test
public void testBasic() 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
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();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// add a new idealState without registering message handling factory
ClusterSetup setupTool = new ClusterSetup(ZK_ADDR);
setupTool.addResourceToCluster(clusterName, "TestDB1", 16, "MasterSlave");
ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
Builder keyBuilder = accessor.keyBuilder();
IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB1"));
idealState.setStateModelFactoryName("TestDB1_Factory");
accessor.setProperty(keyBuilder.idealStates("TestDB1"), idealState);
setupTool.rebalanceStorageCluster(clusterName, "TestDB1", 3);
// assert that we have received OFFLINE->SLAVE messages for all partitions
int totalMsgs = 0;
for (int retry = 0; retry < 5; retry++) {
Thread.sleep(100);
totalMsgs = 0;
for (int i = 0; i < n; i++) {
List<Message> msgs =
accessor.getChildValues(keyBuilder.messages(participants[i].getInstanceName()), true);
totalMsgs += msgs.size();
}
if (totalMsgs == 48) // partition# x replicas
break;
}
Assert
.assertEquals(
totalMsgs,
48,
"Should accumulated 48 unprocessed messages (1 O->S per partition per replica) because TestDB1 is added without state-model-factory but was "
+ totalMsgs);
// register "TestDB1_Factory" state model factory
// Logger.getRootLogger().setLevel(Level.INFO);
for (int i = 0; i < n; i++) {
participants[i].getStateMachineEngine()
.registerStateModelFactory("MasterSlave", new MockMSModelFactory(), "TestDB1_Factory");
}
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// clean up
// wait for all zk callbacks done
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,458 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDistributedCMMain.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.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.ClusterDistributedController;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDistributedCMMain extends ZkTestBase {
private List<String> _clusters = new ArrayList<>();
@Test
public void testDistributedCMMain() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterNamePrefix = className + "_" + methodName;
final int n = 5;
final int clusterNb = 10;
System.out
.println("START " + clusterNamePrefix + " at " + new Date(System.currentTimeMillis()));
// setup 10 clusters
for (int i = 0; i < clusterNb; i++) {
String clusterName = clusterNamePrefix + "0_" + i;
String participantName = "localhost" + i;
String resourceName = "TestDB" + i;
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
participantName, // participant name prefix
resourceName, // resource name prefix
1, // resources
8, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
_clusters.add(clusterName);
}
// setup controller cluster
final String controllerClusterName = "CONTROLLER_" + clusterNamePrefix;
TestHelper.setupCluster("CONTROLLER_" + clusterNamePrefix, ZK_ADDR, 0, // controller
// port
"controller", // participant name prefix
clusterNamePrefix, // resource name prefix
1, // resources
clusterNb, // partitions per resource
n, // number of nodes
3, // replicas
"LeaderStandby", true); // do rebalance
_clusters.add(controllerClusterName);
// start distributed cluster controllers
ClusterDistributedController[] controllers = new ClusterDistributedController[n + n];
for (int i = 0; i < n; i++) {
controllers[i] =
new ClusterDistributedController(ZK_ADDR, controllerClusterName, "controller_" + i);
controllers[i].syncStart();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, controllerClusterName),
30000);
Assert.assertTrue(result, "Controller cluster NOT in ideal state");
// start first cluster
MockParticipantManager[] participants = new MockParticipantManager[n];
final String firstClusterName = clusterNamePrefix + "0_0";
for (int i = 0; i < n; i++) {
String instanceName = "localhost0_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, firstClusterName, instanceName);
participants[i].syncStart();
}
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
firstClusterName));
Assert.assertTrue(result, "first cluster NOT in ideal state");
// add more controllers to controller cluster
ClusterSetup setupTool = new ClusterSetup(ZK_ADDR);
for (int i = 0; i < n; i++) {
String controller = "controller_" + (n + i);
setupTool.addInstanceToCluster(controllerClusterName, controller);
}
setupTool.rebalanceStorageCluster(controllerClusterName, clusterNamePrefix + "0", 6);
for (int i = n; i < 2 * n; i++) {
controllers[i] =
new ClusterDistributedController(ZK_ADDR, controllerClusterName, "controller_" + i);
controllers[i].syncStart();
}
// verify controller cluster
result =
ClusterStateVerifier
.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
controllerClusterName));
Assert.assertTrue(result, "Controller cluster NOT in ideal state");
// verify first cluster
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
firstClusterName));
Assert.assertTrue(result, "first cluster NOT in ideal state");
// stop controller_0-5
ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(controllerClusterName, baseAccessor);
Builder keyBuilder = accessor.keyBuilder();
for (int i = 0; i < n; i++) {
LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
String leaderName = leader.getId();
int j = Integer.parseInt(leaderName.substring(leaderName.lastIndexOf('_') + 1));
controllers[j].syncStop();
result =
ClusterStateVerifier
.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
controllerClusterName));
Assert.assertTrue(result, "Controller cluster NOT in ideal state");
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
firstClusterName));
Assert.assertTrue(result, "first cluster NOT in ideal state");
}
// clean up
// wait for all zk callbacks done
System.out.println("Cleaning up...");
for (int i = 0; i < 2 * n; i++) {
if (controllers[i] != null && controllers[i].isConnected()) {
controllers[i].syncStop();
}
}
for (int i = 0; i < n; i++) {
if (participants[i] != null && participants[i].isConnected()) {
participants[i].syncStop();
}
}
for (String cluster : _clusters) {
deleteCluster(cluster);
}
System.out.println("END " + clusterNamePrefix + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,459 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestExpandCluster.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 org.apache.helix.TestEspressoStorageClusterIdealState;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.util.RebalanceUtil;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestExpandCluster extends ZkStandAloneCMTestBase {
@Test
public void testExpandCluster() throws Exception {
String DB2 = "TestDB2";
int partitions = 30;
int replica = 3;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, DB2, partitions, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, DB2, replica, "keyX");
String DB3 = "TestDB3";
_gSetupTool.addResourceToCluster(CLUSTER_NAME, DB3, partitions, STATE_MODEL);
IdealState testDB0 =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, TEST_DB);
IdealState testDB2 =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, DB2);
IdealState testDB3 =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, DB3);
for (int i = 0; i < 5; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (27960 + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
String command = "-zkSvr localhost:2183 -expandCluster " + CLUSTER_NAME;
ClusterSetup.processCommandLineArgs(command.split(" "));
IdealState testDB0_1 =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, TEST_DB);
IdealState testDB2_1 =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, DB2);
IdealState testDB3_1 =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, DB3);
Map<String, Object> resultOld2 = RebalanceUtil.buildInternalIdealState(testDB2);
Map<String, Object> result2 = RebalanceUtil.buildInternalIdealState(testDB2_1);
TestEspressoStorageClusterIdealState.Verify(result2, partitions, replica - 1);
Double masterKeepRatio = 0.0, slaveKeepRatio = 0.0;
double[] result = TestEspressoStorageClusterIdealState.compareResult(resultOld2, result2);
masterKeepRatio = result[0];
slaveKeepRatio = result[1];
Assert.assertTrue(masterKeepRatio > 0.49 && masterKeepRatio < 0.51);
Assert.assertTrue(testDB3_1.getRecord().getListFields().size() == 0);
// partitions should stay as same
Assert.assertTrue(testDB0_1.getRecord().getListFields().keySet()
.containsAll(testDB0.getRecord().getListFields().keySet()));
Assert.assertTrue(testDB0_1.getRecord().getListFields().size() == testDB0.getRecord()
.getListFields().size());
Assert.assertTrue(testDB2_1.getRecord().getMapFields().keySet()
.containsAll(testDB2.getRecord().getMapFields().keySet()));
Assert.assertTrue(testDB2_1.getRecord().getMapFields().size() == testDB2.getRecord()
.getMapFields().size());
Assert.assertTrue(testDB3_1.getRecord().getMapFields().keySet()
.containsAll(testDB3.getRecord().getMapFields().keySet()));
Assert.assertTrue(testDB3_1.getRecord().getMapFields().size() == testDB3.getRecord()
.getMapFields().size());
Map<String, Object> resultOld = RebalanceUtil.buildInternalIdealState(testDB0);
Map<String, Object> resultNew = RebalanceUtil.buildInternalIdealState(testDB0_1);
result = TestEspressoStorageClusterIdealState.compareResult(resultOld, resultNew);
masterKeepRatio = result[0];
slaveKeepRatio = result[1];
Assert.assertTrue(masterKeepRatio > 0.49 && masterKeepRatio < 0.51);
}
}
| 9,460 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestCleanupExternalView.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.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.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.LiveInstance;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Test clean external-view - if current-state is remove externally, controller should remove the
* orphan external-view
*/
public class TestCleanupExternalView extends ZkUnitTestBase {
private ExternalView _externalView = null;
@Test
public void test() 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
2, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
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();
}
boolean result =
ClusterStateVerifier
.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// disable controller
ZKHelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.enableCluster(clusterName, false);
// wait all pending zk-events being processed, otherwise remove current-state will cause
// controller send O->S message
ZkTestHelper.tryWaitZkEventsCleaned(controller.getZkClient());
// System.out.println("paused controller");
// drop resource
admin.dropResource(clusterName, "TestDB0");
// delete current-state manually, controller shall remove external-view when cluster is enabled
// again
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
// System.out.println("remove current-state");
LiveInstance liveInstance = accessor.getProperty(keyBuilder.liveInstance("localhost_12918"));
accessor.removeProperty(keyBuilder.currentState("localhost_12918", liveInstance.getEphemeralOwner(),
"TestDB0"));
liveInstance = accessor.getProperty(keyBuilder.liveInstance("localhost_12919"));
accessor.removeProperty(
keyBuilder.currentState("localhost_12919", liveInstance.getEphemeralOwner(), "TestDB0"));
// re-enable controller shall remove orphan external-view
// System.out.println("re-enabling controller");
admin.enableCluster(clusterName, true);
result = TestHelper.verify(() -> {
_externalView = accessor.getProperty(keyBuilder.externalView("TestDB0"));
return _externalView == null;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result, "external-view for TestDB0 should be removed, but was: " + _externalView);
// 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,461 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestErrorPartition.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.Collections;
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.manager.zk.ZKHelixAdmin;
import org.apache.helix.mock.participant.ErrTransition;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestErrorPartition extends ZkTestBase {
@Test()
public void testErrorPartition() throws Exception {
String clusterName = getShortClassName();
MockParticipantManager[] participants = new MockParticipantManager[5];
System.out.println("START testErrorPartition() at " + new Date(System.currentTimeMillis()));
ZKHelixAdmin tool = new ZKHelixAdmin(_gZkClient);
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 10, 5, 3,
"MasterSlave", true);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
for (int i = 0; i < 5; i++) {
String instanceName = "localhost_" + (12918 + i);
if (i == 0) {
Map<String, Set<String>> errPartitions = new HashMap<String, Set<String>>() {
{
put("SLAVE-MASTER", TestHelper.setOf("TestDB0_4"));
}
};
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();
}
Map<String, Map<String, String>> errStates = new HashMap<>();
errStates.put("TestDB0", new HashMap<>());
errStates.get("TestDB0").put("TestDB0_4", "localhost_12918");
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName, errStates));
Assert.assertTrue(result);
Map<String, Set<String>> errorStateMap = new HashMap<String, Set<String>>() {
{
put("TestDB0_4", TestHelper.setOf("localhost_12918"));
}
};
// verify "TestDB0_0", "localhost_12918" is in ERROR state
TestHelper.verifyState(clusterName, ZK_ADDR, errorStateMap, "ERROR");
// disable a partition on a node with error state
tool.enablePartition(false, clusterName, "localhost_12918", "TestDB0",
Collections.singletonList("TestDB0_4"));
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName, errStates));
Assert.assertTrue(result);
TestHelper.verifyState(clusterName, ZK_ADDR, errorStateMap, "ERROR");
// disable a node with error state
tool.enableInstance(clusterName, "localhost_12918", false);
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName, errStates));
Assert.assertTrue(result);
// make sure after restart stale ERROR state is gone
tool.enablePartition(true, clusterName, "localhost_12918", "TestDB0",
Collections.singletonList("TestDB0_4"));
tool.enableInstance(clusterName, "localhost_12918", true);
participants[0].syncStop();
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
participants[0] = new MockParticipantManager(ZK_ADDR, clusterName, "localhost_12918");
new Thread(participants[0]).start();
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.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 testErrorPartition() at " + new Date(System.currentTimeMillis()));
}
}
| 9,462 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestCorrectnessOnConnectivityLoss.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.reflect.Method;
import java.util.Map;
import com.google.common.collect.Maps;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.manager.ClusterControllerManager;
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.StateTransitionError;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.spectator.RoutingTableProvider;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.zookeeper.zkclient.ZkServer;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestCorrectnessOnConnectivityLoss {
private static final String ZK_ADDR = "localhost:21892";
private ZkServer _zkServer;
private String _clusterName;
private ClusterControllerManager _controller;
@BeforeMethod
public void beforeMethod(Method testMethod) throws Exception {
_zkServer = TestHelper.startZkServer(ZK_ADDR, null, false);
String className = TestHelper.getTestClassName();
String methodName = testMethod.getName();
_clusterName = className + "_" + methodName;
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant start port
"localhost", // participant host
"resource", // resource name prefix
1, // number of resources
1, // number of partitions
1, // number of participants
1, // number of replicas
"OnlineOffline", // state model
RebalanceMode.FULL_AUTO, // automatic assignment
true); // rebalance
_controller = new ClusterControllerManager(ZK_ADDR, _clusterName, "controller0");
_controller.connect();
}
@AfterMethod
public void afterMethod() {
if (_controller.isConnected()) {
_controller.disconnect();
}
TestHelper.stopZkServer(_zkServer);
}
@Test
public void testParticipant() throws Exception {
Map<String, Integer> stateReachedCounts = Maps.newHashMap();
HelixManager participant =
HelixManagerFactory.getZKHelixManager(_clusterName, "localhost_12918",
InstanceType.PARTICIPANT, ZK_ADDR);
try {
participant.getStateMachineEngine().registerStateModelFactory("OnlineOffline", new MyStateModelFactory(stateReachedCounts));
participant.connect();
Thread.sleep(1000);
// Ensure that the external view coalesces
boolean result = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName));
Assert.assertTrue(result);
// Ensure that there was only one state transition
Assert.assertEquals(stateReachedCounts.size(), 1);
Assert.assertTrue(stateReachedCounts.containsKey("ONLINE"));
Assert.assertEquals(stateReachedCounts.get("ONLINE").intValue(), 1);
// Now let's stop the ZK server; this should do nothing
TestHelper.stopZkServer(_zkServer);
Thread.sleep(1000);
// Verify no change
Assert.assertEquals(stateReachedCounts.size(), 1);
Assert.assertTrue(stateReachedCounts.containsKey("ONLINE"));
Assert.assertEquals(stateReachedCounts.get("ONLINE").intValue(), 1);
} finally {
if (participant.isConnected()) {
participant.disconnect();
}
}
}
@SuppressWarnings("deprecation")
@Test
public void testSpectator() throws Exception {
Map<String, Integer> stateReachedCounts = Maps.newHashMap();
HelixManager participant =
HelixManagerFactory.getZKHelixManager(_clusterName, "localhost_12918",
InstanceType.PARTICIPANT, ZK_ADDR);
RoutingTableProvider routingTableProvider = new RoutingTableProvider();
try {
participant.getStateMachineEngine().registerStateModelFactory("OnlineOffline",
new MyStateModelFactory(stateReachedCounts));
participant.connect();
HelixManager spectator = HelixManagerFactory
.getZKHelixManager(_clusterName, "spectator", InstanceType.SPECTATOR, ZK_ADDR);
spectator.connect();
spectator.addConfigChangeListener(routingTableProvider);
spectator.addExternalViewChangeListener(routingTableProvider);
Thread.sleep(1000);
// Now let's stop the ZK server; this should do nothing
TestHelper.stopZkServer(_zkServer);
Thread.sleep(1000);
// Verify routing table still works
Assert.assertEquals(routingTableProvider.getInstances("resource0", "ONLINE").size(), 1);
Assert.assertEquals(routingTableProvider.getInstances("resource0", "OFFLINE").size(), 0);
} finally {
routingTableProvider.shutdown();
if (participant.isConnected()) {
participant.disconnect();
}
}
}
@StateModelInfo(initialState = "OFFLINE", states = {
"MASTER", "SLAVE", "OFFLINE", "ERROR"
})
public static class MyStateModel extends StateModel {
private final Map<String, Integer> _counts;
public MyStateModel(Map<String, Integer> counts) {
_counts = counts;
}
@Transition(to = "ONLINE", from = "OFFLINE")
public void onBecomeOnlineFromOffline(Message message, NotificationContext context) {
incrementCount(message.getToState());
}
@Transition(to = "OFFLINE", from = "ONLINE")
public void onBecomeOfflineFromOnline(Message message, NotificationContext context) {
incrementCount(message.getToState());
}
@Transition(to = "DROPPED", from = "OFFLINE")
public void onBecomeDroppedFromOffline(Message message, NotificationContext context) {
incrementCount(message.getToState());
}
@Transition(to = "OFFLINE", from = "ERROR")
public void onBecomeOfflineFromError(Message message, NotificationContext context) {
incrementCount(message.getToState());
}
@Transition(to = "DROPPED", from = "ERROR")
public void onBecomeDroppedFromError(Message message, NotificationContext context) {
incrementCount(message.getToState());
}
@Override
public void rollbackOnError(Message message, NotificationContext context,
StateTransitionError error) {
incrementCount("rollback");
}
private synchronized void incrementCount(String toState) {
int current = (_counts.containsKey(toState)) ? _counts.get(toState) : 0;
_counts.put(toState, current + 1);
}
}
public static class MyStateModelFactory extends StateModelFactory<MyStateModel> {
private final Map<String, Integer> _counts;
public MyStateModelFactory(Map<String, Integer> counts) {
_counts = counts;
}
@Override
public MyStateModel createNewStateModel(String resource, String partitionId) {
return new MyStateModel(_counts);
}
}
}
| 9,463 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestBasicSpectator.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.HashMap;
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.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.ExternalView;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestBasicSpectator extends ZkStandAloneCMTestBase implements
ExternalViewChangeListener {
Map<String, Integer> _externalViewChanges = new HashMap<String, Integer>();
@Test
public void TestSpectator() throws Exception {
HelixManager relayHelixManager =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, null, InstanceType.SPECTATOR, ZK_ADDR);
try {
relayHelixManager.connect();
relayHelixManager.addExternalViewChangeListener(this);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "NextDB", 64, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "NextDB", 3);
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
Assert.assertTrue(_externalViewChanges.containsKey("NextDB"));
Assert.assertTrue(_externalViewChanges.containsKey(TEST_DB));
} finally {
if (relayHelixManager.isConnected()) {
relayHelixManager.disconnect();
}
}
}
@Override
public void onExternalViewChange(List<ExternalView> externalViewList,
NotificationContext changeContext) {
for (ExternalView view : externalViewList) {
if (!_externalViewChanges.containsKey(view.getResourceName())) {
_externalViewChanges.put(view.getResourceName(), 1);
} else {
_externalViewChanges.put(view.getResourceName(),
_externalViewChanges.get(view.getResourceName()) + 1);
}
}
}
}
| 9,464 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestResetPartitionState.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.NotificationContext;
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.mock.participant.ErrTransition;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestResetPartitionState extends ZkTestBase {
int _errToOfflineInvoked = 0;
class ErrTransitionWithResetCnt extends ErrTransition {
public ErrTransitionWithResetCnt(Map<String, Set<String>> errPartitions) {
super(errPartitions);
}
@Override
public void doTransition(Message message, NotificationContext context) {
// System.err.println("doReset() invoked");
super.doTransition(message, context);
String fromState = message.getFromState();
String toState = message.getToState();
if (fromState.equals("ERROR") && toState.equals("OFFLINE")) {
_errToOfflineInvoked++;
}
}
}
@Test()
public void testResetPartitionState() 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 a non-exist partition, should throw exception
try {
String command =
"--zkSvr " + ZK_ADDR + " --resetPartition " + clusterName
+ " localhost_12918 TestDB0 TestDB0_nonExist";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("Should throw exception on reset a non-exist partition");
} catch (Exception e) {
// OK
}
// reset one error partition
errPartitions.remove("SLAVE-MASTER");
participants[0].setTransition(new ErrTransitionWithResetCnt(errPartitions));
clearStatusUpdate(clusterName, "localhost_12918", "TestDB0", "TestDB0_4");
_errToOfflineInvoked = 0;
String command =
"--zkSvr " + ZK_ADDR + " --resetPartition " + clusterName
+ " localhost_12918 TestDB0 TestDB0_4";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Thread.sleep(200); // wait reset to be done
try {
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.fail("Should throw exception on reset a partition not in ERROR state");
} catch (Exception e) {
// OK
}
errStateMap.get("TestDB0").remove("TestDB0_4");
result =
ClusterStateVerifier
.verifyByZkCallback((new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName, errStateMap)));
Assert.assertTrue(result, "Cluster verification fails");
Assert.assertEquals(_errToOfflineInvoked, 1);
// reset the other error partition
participants[0].setTransition(new ErrTransitionWithResetCnt(null));
clearStatusUpdate(clusterName, "localhost_12918", "TestDB0", "TestDB0_8");
command =
"--zkSvr " + ZK_ADDR + " --resetPartition " + clusterName
+ " localhost_12918 TestDB0 TestDB0_8";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
result =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, clusterName));
Assert.assertTrue(result, "Cluster verification fails");
Assert.assertEquals(_errToOfflineInvoked, 2, "Should reset 2 partitions");
// 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 clearStatusUpdate(String clusterName, String instance, String resource,
String partition) {
// clear status update for error partition so verify() will not fail on old
// errors
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
LiveInstance liveInstance = accessor.getProperty(keyBuilder.liveInstance(instance));
accessor.removeProperty(keyBuilder.stateTransitionStatus(instance, liveInstance.getEphemeralOwner(),
resource, partition));
}
// TODO: throw exception in reset()
}
| 9,465 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestZkCallbackHandlerLeak.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.AccessOption;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyType;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.ClusterSpectatorManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.integration.manager.ZkTestManager;
import org.apache.helix.manager.zk.CallbackHandler;
import org.apache.helix.model.CurrentState;
import org.apache.helix.spectator.RoutingTableProvider;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.zkclient.IZkChildListener;
import org.apache.helix.zookeeper.zkclient.IZkDataListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestZkCallbackHandlerLeak extends ZkUnitTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestZkCallbackHandlerLeak.class);
@Test
public void testCbHandlerLeakOnParticipantSessionExpiry() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 2;
final int r = 2;
final int taskResourceCount = 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
r, // resources
32, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
final ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
// 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();
// Manually set up task current states
for (int j = 0; j < taskResourceCount; j++) {
_baseAccessor.create(keyBuilder
.taskCurrentState(instanceName, participants[i].getSessionId(), "TestTaskResource_" + j)
.toString(), new ZNRecord("TestTaskResource_" + j), AccessOption.PERSISTENT);
}
}
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
final MockParticipantManager participantManagerToExpire = participants[1];
// check controller zk-watchers
boolean result = TestHelper.verify(() -> {
Map<String, Set<String>> watchers = ZkTestHelper.getListenersBySession(ZK_ADDR);
Set<String> watchPaths = watchers.get("0x" + controller.getSessionId());
// where n is number of nodes and r is number of resources
return watchPaths.size() == (8 + r + (6 + r + taskResourceCount) * n);
}, 2000);
Assert.assertTrue(result, "Controller has incorrect number of zk-watchers.");
// check participant zk-watchers
result = TestHelper.verify(() -> {
Map<String, Set<String>> watchers = ZkTestHelper.getListenersBySession(ZK_ADDR);
Set<String> watchPaths = watchers.get("0x" + participantManagerToExpire.getSessionId());
// participant should have 1 zk-watcher: 1 for MESSAGE
return watchPaths.size() == 1;
}, 2000);
Assert.assertTrue(result, "Participant should have 1 zk-watcher. MESSAGES->HelixTaskExecutor");
// check HelixManager#_handlers
int controllerHandlerNb = controller.getHandlers().size();
int particHandlerNb = participantManagerToExpire.getHandlers().size();
Assert.assertEquals(controllerHandlerNb, 8 + 4 * n,
"HelixController should have 16 (8+4n) callback handlers for 2 (n) participant");
Assert.assertEquals(particHandlerNb, 1,
"HelixParticipant should have 1 (msg->HelixTaskExecutor) callback handlers");
// expire the session of participant
System.out.println("Expiring participant session...");
String oldSessionId = participantManagerToExpire.getSessionId();
ZkTestHelper.expireSession(participantManagerToExpire.getZkClient());
String newSessionId = participantManagerToExpire.getSessionId();
System.out.println(
"Expired participant session. oldSessionId: " + oldSessionId + ", newSessionId: "
+ newSessionId);
result =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, clusterName));
Assert.assertTrue(result);
// check controller zk-watchers
result = TestHelper.verify(() -> {
Map<String, Set<String>> watchers = ZkTestHelper.getListenersBySession(ZK_ADDR);
Set<String> watchPaths = watchers.get("0x" + controller.getSessionId());
// where n is number of nodes and r is number of resources
// one participant is disconnected, and its task current states are removed
return watchPaths.size() == (8 + r + (6 + r + taskResourceCount) * (n - 1) + 6 + r);
}, 2000);
Assert.assertTrue(result, "Controller has incorrect number of zk-watchers after session expiry.");
// check participant zk-watchers
result = TestHelper.verify(() -> {
Map<String, Set<String>> watchers = ZkTestHelper.getListenersBySession(ZK_ADDR);
Set<String> watchPaths = watchers.get("0x" + participantManagerToExpire.getSessionId());
// participant should have 1 zk-watcher: 1 for MESSAGE
return watchPaths.size() == 1;
}, 2000);
Assert.assertTrue(result, "Participant should have 1 zk-watcher after session expiry.");
// check handlers
int handlerNb = controller.getHandlers().size();
Assert.assertEquals(handlerNb, controllerHandlerNb,
"controller callback handlers should not increase after participant session expiry");
handlerNb = participantManagerToExpire.getHandlers().size();
Assert.assertEquals(handlerNb, particHandlerNb,
"participant callback handlers should not increase after participant session expiry");
// 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()));
}
@Test
public void testCbHandlerLeakOnControllerSessionExpiry() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 2;
final int r = 1;
final int taskResourceCount = 1;
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
r, // resources
32, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
final ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
// 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();
// Manually set up task current states
for (int j = 0; j < taskResourceCount; j++) {
_baseAccessor.create(keyBuilder
.taskCurrentState(instanceName, participants[i].getSessionId(), "TestTaskResource_" + j)
.toString(), new ZNRecord("TestTaskResource_" + j), AccessOption.PERSISTENT);
}
}
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
final MockParticipantManager participantManager = participants[0];
// wait until we get all the listeners registered
TestHelper.verify(() -> {
int controllerHandlerNb = controller.getHandlers().size();
int particHandlerNb = participantManager.getHandlers().size();
if (controllerHandlerNb == 10 && particHandlerNb == 2)
return true;
else
return false;
}, 1000);
int controllerHandlerNb = controller.getHandlers().size();
int particHandlerNb = participantManager.getHandlers().size();
Assert.assertEquals(controllerHandlerNb, 8 + 4 * n,
"HelixController should have 16 (8+4n) callback handlers for 2 participant, but was "
+ controllerHandlerNb + ", " + printHandlers(controller));
Assert.assertEquals(particHandlerNb, 1,
"HelixParticipant should have 1 (msg->HelixTaskExecutor) callback handler, but was "
+ particHandlerNb + ", " + printHandlers(participantManager));
// expire controller
System.out.println("Expiring controller session...");
String oldSessionId = controller.getSessionId();
ZkTestHelper.expireSession(controller.getZkClient());
String newSessionId = controller.getSessionId();
System.out.println(
"Expired controller session. oldSessionId: " + oldSessionId + ", newSessionId: "
+ newSessionId);
Assert.assertTrue(verifier.verifyByPolling());
// check controller zk-watchers
boolean result = TestHelper.verify(() -> {
Map<String, Set<String>> watchers = ZkTestHelper.getListenersBySession(ZK_ADDR);
Set<String> watchPaths = watchers.get("0x" + controller.getSessionId());
System.err.println("controller watch paths after session expiry: " + watchPaths.size());
// where r is number of resources and n is number of nodes
// task resource count does not attribute to ideal state watch paths
int expected = (8 + r + (6 + r + taskResourceCount) * n);
return watchPaths.size() == expected;
}, 2000);
Assert.assertTrue(result, "Controller has incorrect zk-watchers after session expiry.");
// check participant zk-watchers
result = TestHelper.verify(() -> {
Map<String, Set<String>> watchers = ZkTestHelper.getListenersBySession(ZK_ADDR);
Set<String> watchPaths = watchers.get("0x" + participantManager.getSessionId());
// participant should have 1 zk-watcher: 1 for MESSAGE
return watchPaths.size() == 1;
}, 2000);
Assert.assertTrue(result, "Participant should have 1 zk-watcher after session expiry.");
// check HelixManager#_handlers
int handlerNb = controller.getHandlers().size();
Assert.assertEquals(handlerNb, controllerHandlerNb,
"controller callback handlers should not increase after participant session expiry, but was "
+ printHandlers(controller));
handlerNb = participantManager.getHandlers().size();
Assert.assertEquals(handlerNb, particHandlerNb,
"participant callback handlers should not increase after participant session expiry, but was "
+ printHandlers(participantManager));
// 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()));
}
@Test
public void testDanglingCallbackHandler() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 3;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, // resource
32, // partitions
n, // nodes
2, // replicas
"MasterSlave", true);
final ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
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();
}
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// Routing provider is a spectator in Helix. Currentstate based RP listens on all the
// currentstate changes of all the clusters. They are a source of leaking of watch in
// Zookeeper server.
ClusterSpectatorManager rpManager = new ClusterSpectatorManager(ZK_ADDR, clusterName, "router");
rpManager.syncStart();
RoutingTableProvider rp = new RoutingTableProvider(rpManager, PropertyType.CURRENTSTATES);
//TODO: The following three sleep() is not the best practice. On the other hand, we don't have the testing
// facilities to avoid them yet. We will enhance later.
Thread.sleep(5000);
// expire RoutingProvider would create dangling CB
LOG.info("expire rp manager session:", rpManager.getSessionId());
ZkTestHelper.expireSession(rpManager.getZkClient());
LOG.info("rp manager new session:", rpManager.getSessionId());
Thread.sleep(5000);
MockParticipantManager participantToExpire = participants[0];
String oldSessionId = participantToExpire.getSessionId();
// expire participant session; leaked callback handler used to be not reset() and be removed from ZkClient
LOG.info("Expire participant: " + participantToExpire.getInstanceName() + ", session: "
+ participantToExpire.getSessionId());
ZkTestHelper.expireSession(participantToExpire.getZkClient());
String newSessionId = participantToExpire.getSessionId();
LOG.info(participantToExpire.getInstanceName() + " oldSessionId: " + oldSessionId
+ ", newSessionId: " + newSessionId);
Thread.sleep(5000);
Map<String, Set<IZkChildListener>> childListeners =
ZkTestHelper.getZkChildListener(rpManager.getZkClient());
for (String path : childListeners.keySet()) {
Assert.assertTrue(childListeners.get(path).size() <= 1);
}
Map<String, List<String>> rpWatchPaths = ZkTestHelper.getZkWatch(rpManager.getZkClient());
List<String> existWatches = rpWatchPaths.get("existWatches");
Assert.assertTrue(existWatches.isEmpty());
// clean up
controller.syncStop();
rp.shutdown();
Assert.assertTrue(rpManager.getHandlers().isEmpty(),
"HelixManager should not have any callback handlers after shutting down RoutingTableProvider");
rpManager.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
public void testCurrentStatePathLeakingByAsycRemoval() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 3;
final String zkAddr = ZK_ADDR;
final int mJobUpdateCnt = 500;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, zkAddr, 12918, "localhost", "TestDB", 1, // resource
32, // partitions
n, // nodes
2, // replicas
"MasterSlave", true);
final ClusterControllerManager controller =
new ClusterControllerManager(zkAddr, clusterName, "controller_0");
controller.syncStart();
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(zkAddr, 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());
ClusterSpectatorManager rpManager = new ClusterSpectatorManager(ZK_ADDR, clusterName, "router");
rpManager.syncStart();
RoutingTableProvider rp = new RoutingTableProvider(rpManager, PropertyType.CURRENTSTATES);
MockParticipantManager jobParticipant = participants[0];
String jobSessionId = jobParticipant.getSessionId();
HelixDataAccessor jobAccessor = jobParticipant.getHelixDataAccessor();
PropertyKey.Builder jobKeyBuilder = new PropertyKey.Builder(clusterName);
PropertyKey db0key =
jobKeyBuilder.currentState(jobParticipant.getInstanceName(), jobSessionId, "TestDB0");
CurrentState db0 = jobAccessor.getProperty(db0key);
PropertyKey jobKey =
jobKeyBuilder.currentState(jobParticipant.getInstanceName(), jobSessionId, "BackupQueue");
CurrentState cs = new CurrentState("BackupQueue");
cs.setSessionId(jobSessionId);
cs.setStateModelDefRef(db0.getStateModelDefRef());
Map<String, List<String>> rpWatchPaths = ZkTestHelper.getZkWatch(rpManager.getZkClient());
Assert.assertFalse(rpWatchPaths.get("dataWatches").contains(jobKey.getPath()));
LOG.info("add job");
for (int i = 0; i < mJobUpdateCnt; i++) {
jobAccessor.setProperty(jobKey, cs);
}
// verify new watcher is installed on the new node
boolean result = TestHelper.verify(
() -> ZkTestHelper.getListenersByZkPath(ZK_ADDR).keySet().contains(jobKey.getPath())
&& ZkTestHelper.getZkWatch(rpManager.getZkClient()).get("dataWatches")
.contains(jobKey.getPath()), TestHelper.WAIT_DURATION);
Assert.assertTrue(result,
"Should get initial clusterConfig callback invoked and add data watchers");
LOG.info("remove job");
jobParticipant.getZkClient().delete(jobKey.getPath());
// validate the job watch is not leaked.
Thread.sleep(5000);
Map<String, Set<String>> listenersByZkPath = ZkTestHelper.getListenersByZkPath(ZK_ADDR);
Assert.assertFalse(listenersByZkPath.keySet().contains(jobKey.getPath()));
rpWatchPaths = ZkTestHelper.getZkWatch(rpManager.getZkClient());
List<String> existWatches = rpWatchPaths.get("existWatches");
Assert.assertTrue(existWatches.isEmpty());
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
rp.shutdown();
Assert.assertTrue(rpManager.getHandlers().isEmpty(),
"HelixManager should not have any callback handlers after shutting down RoutingTableProvider");
rpManager.syncStop();
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testRemoveUserCbHandlerOnPathRemoval() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 3;
final String zkAddr = ZK_ADDR;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, zkAddr, 12918, "localhost", "TestDB", 1, // resource
32, // partitions
n, // nodes
2, // replicas
"MasterSlave", true);
final ClusterControllerManager controller =
new ClusterControllerManager(zkAddr, clusterName, "controller_0");
controller.syncStart();
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(zkAddr, clusterName, instanceName);
participants[i].syncStart();
// register a controller listener on participant_0
if (i == 0) {
MockParticipantManager manager = participants[0];
manager.addCurrentStateChangeListener((instanceName1, statesInfo, changeContext) -> {
// To change body of implemented methods use File | Settings | File Templates.
}, manager.getInstanceName(), manager.getSessionId());
}
}
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
MockParticipantManager participantToExpire = participants[0];
String oldSessionId = participantToExpire.getSessionId();
PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
// check manager#hanlders
Assert.assertEquals(participantToExpire.getHandlers().size(), 2,
"Should have 2 handlers: CURRENTSTATE/{sessionId}, and MESSAGES");
// check zkclient#listeners
Map<String, Set<IZkDataListener>> dataListeners =
ZkTestHelper.getZkDataListener(participantToExpire.getZkClient());
Map<String, Set<IZkChildListener>> childListeners =
ZkTestHelper.getZkChildListener(participantToExpire.getZkClient());
Assert.assertEquals(dataListeners.size(), 1,
"Should have 1 path (CURRENTSTATE/{sessionId}/TestDB0) which has 1 data-listeners");
String path =
keyBuilder.currentState(participantToExpire.getInstanceName(), oldSessionId, "TestDB0")
.getPath();
Assert.assertEquals(dataListeners.get(path).size(), 1, "Should have 1 data-listeners on path: "
+ path);
Assert
.assertEquals(childListeners.size(), 2,
"Should have 2 paths (CURRENTSTATE/{sessionId}, and MESSAGES) each of which has 1 child-listener");
path = keyBuilder.currentStates(participantToExpire.getInstanceName(), oldSessionId).getPath();
Assert.assertEquals(childListeners.get(path).size(), 1,
"Should have 1 child-listener on path: " + path);
path = keyBuilder.messages(participantToExpire.getInstanceName()).getPath();
Assert.assertEquals(childListeners.get(path).size(), 1,
"Should have 1 child-listener on path: " + path);
path = keyBuilder.controller().getPath();
Assert.assertNull(childListeners.get(path), "Should have no child-listener on path: " + path);
// check zookeeper#watches on client side
Map<String, List<String>> watchPaths =
ZkTestHelper.getZkWatch(participantToExpire.getZkClient());
Assert
.assertEquals(watchPaths.get("dataWatches").size(), 3,
"Should have 3 data-watches: CURRENTSTATE/{sessionId}, CURRENTSTATE/{sessionId}/TestDB, MESSAGES");
Assert.assertEquals(watchPaths.get("childWatches").size(), 2,
"Should have 2 child-watches: MESSAGES, and CURRENTSTATE/{sessionId}");
// expire localhost_12918
System.out.println(
"Expire participant: " + participantToExpire.getInstanceName() + ", session: "
+ participantToExpire.getSessionId());
ZkTestHelper.expireSession(participantToExpire.getZkClient());
String newSessionId = participantToExpire.getSessionId();
System.out.println(participantToExpire.getInstanceName() + " oldSessionId: " + oldSessionId
+ ", newSessionId: " + newSessionId);
verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// check manager#hanlders
Assert
.assertEquals(
participantToExpire.getHandlers().size(),
1,
"Should have 1 handlers: MESSAGES. CURRENTSTATE/{sessionId} handler should be removed by CallbackHandler#handleChildChange()");
// check zkclient#listeners
dataListeners = ZkTestHelper.getZkDataListener(participantToExpire.getZkClient());
childListeners = ZkTestHelper.getZkChildListener(participantToExpire.getZkClient());
Assert.assertTrue(dataListeners.isEmpty(), "Should have no data-listeners");
Assert
.assertEquals(
childListeners.size(),
2,
"Should have 2 paths (CURRENTSTATE/{oldSessionId}, and MESSAGES). "
+ "CONTROLLER and MESSAGE has 1 child-listener each. CURRENTSTATE/{oldSessionId} doesn't have listener (ZkClient doesn't remove empty childListener set. probably a ZkClient bug. see ZkClient#unsubscribeChildChange())");
path = keyBuilder.currentStates(participantToExpire.getInstanceName(), oldSessionId).getPath();
Assert.assertEquals(childListeners.get(path).size(), 0,
"Should have no child-listener on path: " + path);
path = keyBuilder.messages(participantToExpire.getInstanceName()).getPath();
Assert.assertEquals(childListeners.get(path).size(), 1,
"Should have 1 child-listener on path: " + path);
path = keyBuilder.controller().getPath();
Assert.assertNull(childListeners.get(path),
"Should have no child-listener on path: " + path);
// check zookeeper#watches on client side
watchPaths = ZkTestHelper.getZkWatch(participantToExpire.getZkClient());
Assert.assertEquals(watchPaths.get("dataWatches").size(), 1,
"Should have 1 data-watches: MESSAGES");
Assert.assertEquals(watchPaths.get("childWatches").size(), 1,
"Should have 1 child-watches: MESSAGES");
// In this test participant0 also register to its own cocurrent state with a callbackhandler
// When session expiration happens, the current state parent path would also changes. However,
// an exists watch would still be installed by event pushed to ZkCLient event thread by
// fireAllEvent() children even path on behalf of old session callbackhandler. By the time this
// event gets invoked, the old session callbackhandler was removed, but the event would still
// install a exist watch for old session.
// The closest similar case in production is that router/controller has an session expiration at
// the same time as participant.
// Currently there are many places to register watch in Zookeeper over the evolution of Helix
// and ZkClient. We plan for further simplify the logic of watch installation next.
boolean result = TestHelper.verify(()-> {
Map<String, List<String>> wPaths = ZkTestHelper.getZkWatch(participantToExpire.getZkClient());
return wPaths.get("existWatches").size() == 1;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result,
"Should have 1 exist-watches: CURRENTSTATE/{oldSessionId}");
// another session expiry on localhost_12918 should clear the two exist-watches on
// CURRENTSTATE/{oldSessionId}
System.out.println(
"Expire participant: " + participantToExpire.getInstanceName() + ", session: "
+ participantToExpire.getSessionId());
ZkTestHelper.expireSession(participantToExpire.getZkClient());
Assert.assertTrue(verifier.verifyByPolling());
// check zookeeper#watches on client side
watchPaths = ZkTestHelper.getZkWatch(participantToExpire.getZkClient());
Assert.assertEquals(watchPaths.get("dataWatches").size(), 1,
"Should have 1 data-watches: MESSAGES");
Assert.assertEquals(watchPaths.get("childWatches").size(), 1,
"Should have 1 child-watches: MESSAGES");
Assert
.assertEquals(
watchPaths.get("existWatches").size(),
0,
"Should have no exist-watches. exist-watches on CURRENTSTATE/{oldSessionId} and CURRENTSTATE/{oldSessionId}/TestDB0 should be cleared during handleNewSession");
// 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()));
}
// debug code
static String printHandlers(ZkTestManager manager) {
StringBuilder sb = new StringBuilder();
List<CallbackHandler> handlers = manager.getHandlers();
sb.append(manager.getInstanceName() + " has " + handlers.size() + " cb-handlers. [");
for (int i = 0; i < handlers.size(); i++) {
CallbackHandler handler = handlers.get(i);
String path = handler.getPath();
sb.append(path.substring(manager.getClusterName().length() + 1) + ": "
+ handler.getListener());
if (i < (handlers.size() - 1)) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
| 9,466 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestExternalViewUpdates.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.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.ZkBaseDataAccessor;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterStateVerifier.MasterNbInExtViewVerifier;
import org.apache.zookeeper.data.Stat;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestExternalViewUpdates extends ZkTestBase {
@Test
public void testExternalViewUpdates() throws Exception {
System.out.println("START testExternalViewUpdates at " + new Date(System.currentTimeMillis()));
String clusterName = getShortClassName();
int numResource = 10;
int numPartition = 1;
int numReplica = 1;
int numNode = 5;
int startPort = 12918;
MockParticipantManager[] participants = new MockParticipantManager[numNode];
TestHelper.setupCluster(clusterName, ZK_ADDR, startPort, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
numResource, // resources
numPartition, // partitions per resource
numNode, // number of nodes
numReplica, // replicas
"MasterSlave", true); // do rebalance
// start participants
for (int i = 0; i < numNode; i++) {
String instanceName = "localhost_" + (startPort + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// start controller after participants to trigger rebalance immediately
// after the controller is ready
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
boolean result =
ClusterStateVerifier
.verifyByZkCallback(new MasterNbInExtViewVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// 10 Resources, 1 partition, 1 replica, so there are at most 10 ZK writes for EV (assume)
// worst case that no event is batched in controller. Therefore, EV version should be < 10
Builder keyBuilder = new Builder(clusterName);
BaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient);
String parentPath = keyBuilder.externalViews().getPath();
List<String> childNames = accessor.getChildNames(parentPath, 0);
List<String> paths = new ArrayList<>();
for (String name : childNames) {
paths.add(parentPath + "/" + name);
}
int maxEV = numResource * numPartition * numReplica;
for (String path : paths) {
Stat stat = accessor.getStat(path, 0);
Assert.assertTrue(stat.getVersion() <= maxEV,
"ExternalView should be updated at most " + maxEV + " times");
}
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END testExternalViewUpdates at " + new Date(System.currentTimeMillis()));
}
}
| 9,467 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestHelixInstanceTag.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.HashSet;
import java.util.Set;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestHelixInstanceTag extends ZkStandAloneCMTestBase {
@Test
public void testInstanceTag() throws Exception {
HelixManager manager = _controller;
HelixDataAccessor accessor = manager.getHelixDataAccessor();
String DB2 = "TestDB2";
int partitions = 100;
String DB2tag = "TestDB2_tag";
int replica = 2;
for (int i = 0; i < 2; i++) {
String instanceName = "localhost_" + (12918 + i);
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, instanceName, DB2tag);
}
_gSetupTool.addResourceToCluster(CLUSTER_NAME, DB2, partitions, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, DB2, DB2tag, replica);
boolean result =
ClusterStateVerifier
.verifyByZkCallback((new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
CLUSTER_NAME)));
Assert.assertTrue(result, "Cluster verification fails");
ExternalView ev = accessor.getProperty(accessor.keyBuilder().externalView(DB2));
Set<String> hosts = new HashSet<String>();
for (String p : ev.getPartitionSet()) {
for (String hostName : ev.getStateMap(p).keySet()) {
InstanceConfig config =
accessor.getProperty(accessor.keyBuilder().instanceConfig(hostName));
Assert.assertTrue(config.containsTag(DB2tag));
hosts.add(hostName);
}
}
Assert.assertEquals(hosts.size(), 2);
String DB3 = "TestDB3";
String DB3Tag = "TestDB3_tag";
partitions = 10;
replica = 3;
for (int i = 1; i < 5; i++) {
String instanceName = "localhost_" + (12918 + i);
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, instanceName, DB3Tag);
}
_gSetupTool.addResourceToCluster(CLUSTER_NAME, DB3, partitions, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, DB3, DB3Tag, replica);
result =
ClusterStateVerifier
.verifyByZkCallback((new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
CLUSTER_NAME)));
Assert.assertTrue(result, "Cluster verification fails");
ev = accessor.getProperty(accessor.keyBuilder().externalView(DB3));
hosts = new HashSet<String>();
for (String p : ev.getPartitionSet()) {
for (String hostName : ev.getStateMap(p).keySet()) {
InstanceConfig config =
accessor.getProperty(accessor.keyBuilder().instanceConfig(hostName));
Assert.assertTrue(config.containsTag(DB3Tag));
hosts.add(hostName);
}
}
Assert.assertEquals(hosts.size(), 4);
}
}
| 9,468 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestZkSessionExpiry.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.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import com.google.common.collect.ImmutableList;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.messaging.handling.HelixTaskResult;
import org.apache.helix.messaging.handling.MessageHandler;
import org.apache.helix.messaging.handling.MultiTypeMessageHandlerFactory;
import org.apache.helix.model.Message;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestZkSessionExpiry extends ZkUnitTestBase {
private final static String DUMMY_MSG_TYPE = "DUMMY";
static class DummyMessageHandler extends MessageHandler {
final Set<String> _handledMsgSet;
DummyMessageHandler(Message message, NotificationContext context, Set<String> handledMsgSet) {
super(message, context);
_handledMsgSet = handledMsgSet;
}
@Override
public HelixTaskResult handleMessage() {
_handledMsgSet.add(_message.getId());
HelixTaskResult ret = new HelixTaskResult();
ret.setSuccess(true);
return ret;
}
@Override
public void onError(Exception e, ErrorCode code, ErrorType type) {
// Do nothing
}
}
static class DummyMessageHandlerFactory implements MultiTypeMessageHandlerFactory {
final Set<String> _handledMsgSet;
DummyMessageHandlerFactory(Set<String> handledMsgSet) {
_handledMsgSet = handledMsgSet;
}
@Override
public MessageHandler createHandler(Message message, NotificationContext context) {
return new DummyMessageHandler(message, context, _handledMsgSet);
}
@Override
public List<String> getMessageTypes() {
return ImmutableList.of(DUMMY_MSG_TYPE);
}
@Override
public void reset() {
// Do nothing
}
}
@Test
public void testMsgHdlrFtyReRegistration() 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
8, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
Set<String> handledMsgSet = new HashSet<>();
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].getMessagingService().registerMessageHandlerFactory(DUMMY_MSG_TYPE,
new DummyMessageHandlerFactory(handledMsgSet));
participants[i].syncStart();
}
boolean result = ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// trigger dummy message handler
checkDummyMsgHandler(participants[0], handledMsgSet);
// expire localhost_12918
ZkTestHelper.expireSession(participants[0].getZkClient());
result = ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// trigger dummy message handler again
checkDummyMsgHandler(participants[0], handledMsgSet);
// 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()));
}
/**
* trigger dummy message handler and verify it's invoked
* @param manager
* @param handledMsgSet
* @throws Exception
*/
private static void checkDummyMsgHandler(HelixManager manager, final Set<String> handledMsgSet)
throws Exception {
final Message aMsg = newMsg();
HelixDataAccessor accessor = manager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.message(manager.getInstanceName(), aMsg.getId()), aMsg);
boolean result = TestHelper.verify(() -> handledMsgSet.contains(aMsg.getId()), 5 * 1000);
Assert.assertTrue(result);
}
private static Message newMsg() {
Message msg = new Message(DUMMY_MSG_TYPE, UUID.randomUUID().toString());
msg.setTgtSessionId("*");
msg.setTgtName("localhost_12918");
return msg;
}
}
| 9,469 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/SinglePartitionLeaderStandByTest.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 org.apache.helix.HelixConstants;
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.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* This is a simple integration test. We will use this until we have framework
* which helps us write integration tests easily
*/
public class SinglePartitionLeaderStandByTest extends ZkTestBase {
@Test
public void test()
throws Exception {
String clusterName = TestHelper.getTestMethodName();
int n = 4;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
// Thread.currentThread().join();
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
0, // replicas
"LeaderStandby", RebalanceMode.FULL_AUTO, false); // dont rebalance
// rebalance ideal-state to use ANY_LIVEINSTANCE for preference list
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
PropertyKey key = keyBuilder.idealStates("TestDB0");
IdealState idealState = accessor.getProperty(key);
idealState.setReplicas(HelixConstants.StateModelToken.ANY_LIVEINSTANCE.toString());
idealState.getRecord()
.setListField("TestDB0_0", Arrays.asList(HelixConstants.StateModelToken.ANY_LIVEINSTANCE.toString()));
accessor.setProperty(key, idealState);
ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
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();
}
boolean result = ClusterStateVerifier
.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
//stop the first participatn
participants[0].syncStop();
Thread.sleep(10000);
for (int i = 0; i < 1; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// 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,470 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestWeightBasedRebalanceUtil.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.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.helix.HelixException;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.api.config.RebalanceConfig;
import org.apache.helix.api.rebalancer.constraint.AbstractRebalanceHardConstraint;
import org.apache.helix.api.rebalancer.constraint.AbstractRebalanceSoftConstraint;
import org.apache.helix.api.rebalancer.constraint.dataprovider.PartitionWeightProvider;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.common.PartitionStateMap;
import org.apache.helix.controller.common.ResourcesStateMap;
import org.apache.helix.controller.rebalancer.constraint.PartitionWeightAwareEvennessConstraint;
import org.apache.helix.controller.rebalancer.constraint.TotalCapacityConstraint;
import org.apache.helix.controller.rebalancer.constraint.dataprovider.MockCapacityProvider;
import org.apache.helix.controller.rebalancer.constraint.dataprovider.MockPartitionWeightProvider;
import org.apache.helix.controller.rebalancer.constraint.dataprovider.ZkBasedCapacityProvider;
import org.apache.helix.controller.rebalancer.constraint.dataprovider.ZkBasedPartitionWeightProvider;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.OnlineOfflineSMD;
import org.apache.helix.model.Partition;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.util.WeightAwareRebalanceUtil;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.apache.helix.controller.rebalancer.constraint.dataprovider.ZkBasedPartitionWeightProvider.DEFAULT_WEIGHT_VALUE;
public class TestWeightBasedRebalanceUtil extends ZkTestBase {
private static String CLUSTER_NAME;
final String resourceNamePrefix = "resource";
final int nParticipants = 40;
final int nResources = 20;
final int nPartitions = 100;
final int nReplicas = 3;
final int defaultCapacity = 6000; // total = 6000*40 = 240000
final int resourceWeight = 10; // total = 20*100*3*10 = 60000
final String topState = "ONLINE";
final List<String> resourceNames = new ArrayList<>();
final List<String> instanceNames = new ArrayList<>();
final List<String> partitions = new ArrayList<>(nPartitions);
final List<ResourceConfig> resourceConfigs = new ArrayList<>();
final LinkedHashMap<String, Integer> states = new LinkedHashMap<>(2);
final ClusterConfig clusterConfig = new ClusterConfig(CLUSTER_NAME);
final List<InstanceConfig> instanceConfigs = new ArrayList<>();
@BeforeClass
public void beforeClass() {
System.out.println(
"START " + getClass().getSimpleName() + " at " + new Date(System.currentTimeMillis()));
CLUSTER_NAME = "MockCluster" + getShortClassName();
for (int i = 0; i < nParticipants; i++) {
instanceNames.add("node" + i);
}
for (int i = 0; i < nPartitions; i++) {
partitions.add(Integer.toString(i));
}
for (int i = 0; i < nResources; i++) {
resourceNames.add(resourceNamePrefix + i);
ResourceConfig.Builder resourcBuilder = new ResourceConfig.Builder(resourceNamePrefix + i);
resourcBuilder.setStateModelDefRef("OnlineOffline");
resourcBuilder.setNumReplica(nReplicas);
for (String partition : partitions) {
resourcBuilder.setPreferenceList(partition, Collections.EMPTY_LIST);
}
resourceConfigs.add(resourcBuilder.build());
}
setupMockCluster();
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
}
@AfterClass
public void afterClass() {
deleteCluster(CLUSTER_NAME);
}
private void setupMockCluster() {
for (String instance : instanceNames) {
InstanceConfig config = new InstanceConfig(instance);
instanceConfigs.add(config);
}
states.put("OFFLINE", 0);
states.put(topState, nReplicas);
}
private Map<String, Integer> checkPartitionUsage(ResourcesStateMap assignment,
PartitionWeightProvider weightProvider) {
Map<String, Integer> weightCount = new HashMap<>();
for (String resource : assignment.resourceSet()) {
PartitionStateMap partitionMap = assignment.getPartitionStateMap(resource);
for (Partition partition : partitionMap.partitionSet()) {
// check states
Map<String, Integer> stateCount = new HashMap<>(states);
Map<String, String> stateMap = partitionMap.getPartitionMap(partition);
for (String state : stateMap.values()) {
Assert.assertTrue(stateCount.containsKey(state));
stateCount.put(state, stateCount.get(state) - 1);
}
for (int count : stateCount.values()) {
Assert.assertEquals(count, 0);
}
// report weight
int partitionWeight =
weightProvider.getPartitionWeight(resource, partition.getPartitionName());
for (String instance : partitionMap.getPartitionMap(partition).keySet()) {
if (!weightCount.containsKey(instance)) {
weightCount.put(instance, partitionWeight);
} else {
weightCount.put(instance, weightCount.get(instance) + partitionWeight);
}
}
}
}
return weightCount;
}
private void validateWeight(PartitionWeightProvider provider) {
for (String resource : resourceNames) {
for (String partition : partitions) {
int weight = provider.getPartitionWeight(resource, partition);
if (resource.equals(resourceNames.get(0))) {
if (partition.equals(partitions.get(0))) {
Assert.assertEquals(weight, resourceWeight * 3);
} else {
Assert.assertEquals(weight, resourceWeight * 2);
}
} else if (resource.equals(resourceNames.get(1))) {
if (partition.equals(partitions.get(0))) {
Assert.assertEquals(weight, resourceWeight * 3);
} else {
Assert.assertEquals(weight, resourceWeight);
}
} else {
Assert.assertEquals(weight, resourceWeight);
}
}
}
}
@Test
public void testRebalance() {
// capacity / weight
Map<String, Integer> capacity = new HashMap<>();
for (String instance : instanceNames) {
capacity.put(instance, defaultCapacity);
}
MockCapacityProvider capacityProvider = new MockCapacityProvider(capacity, defaultCapacity);
MockPartitionWeightProvider weightProvider = new MockPartitionWeightProvider(resourceWeight);
TotalCapacityConstraint capacityConstraint =
new TotalCapacityConstraint(weightProvider, capacityProvider);
PartitionWeightAwareEvennessConstraint evenConstraint =
new PartitionWeightAwareEvennessConstraint(weightProvider, capacityProvider);
WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs, null,
Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
int max = Collections.max(weightCount.values());
int min = Collections.min(weightCount.values());
// Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of
// participant capacity in max.
Assert.assertTrue((max - min) <= defaultCapacity / 100);
}
@Test
public void testZkBasedCapacityProvider() {
Map<String, Integer> resourceDefaultWeightMap = new HashMap<>();
resourceDefaultWeightMap.put(resourceNames.get(0), resourceWeight * 2);
Map<String, Map<String, Integer>> partitionWeightMap = new HashMap<>();
partitionWeightMap.put(resourceNames.get(0),
Collections.singletonMap(partitions.get(0), resourceWeight * 3));
partitionWeightMap.put(resourceNames.get(1),
Collections.singletonMap(partitions.get(0), resourceWeight * 3));
ZkBasedPartitionWeightProvider weightProvider =
new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "Test");
weightProvider.updateWeights(resourceDefaultWeightMap, partitionWeightMap, resourceWeight);
// verify before persist
validateWeight(weightProvider);
// persist get values back
weightProvider.persistWeights();
// verify after persist
weightProvider = new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "Test");
validateWeight(weightProvider);
weightProvider = new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "Fack");
for (String resource : resourceNames) {
for (String partition : partitions) {
Assert.assertEquals(weightProvider.getPartitionWeight(resource, partition),
DEFAULT_WEIGHT_VALUE);
}
}
// update with invalid value
weightProvider.updateWeights(Collections.EMPTY_MAP, Collections.EMPTY_MAP, -1);
try {
weightProvider.persistWeights();
Assert.fail("Should fail to persist invalid weight information.");
} catch (HelixException hex) {
// expected
}
Map<String, Integer> capacity = new HashMap<>();
Map<String, Integer> usage = new HashMap<>();
for (int i = 0; i < instanceNames.size(); i++) {
capacity.put(instanceNames.get(i), defaultCapacity + i);
usage.put(instanceNames.get(i), i);
}
ZkBasedCapacityProvider capacityProvider =
new ZkBasedCapacityProvider(ZK_ADDR, CLUSTER_NAME, "Test");
capacityProvider.updateCapacity(capacity, usage, defaultCapacity);
for (String instance : instanceNames) {
Assert.assertEquals(capacityProvider.getParticipantCapacity(instance),
capacity.get(instance).intValue());
Assert.assertEquals(capacityProvider.getParticipantUsage(instance),
usage.get(instance).intValue());
}
// persist get values back
capacityProvider.persistCapacity();
capacityProvider = new ZkBasedCapacityProvider(ZK_ADDR, CLUSTER_NAME, "Test");
for (String instance : instanceNames) {
Assert.assertEquals(capacityProvider.getParticipantCapacity(instance),
capacity.get(instance).intValue());
Assert.assertEquals(capacityProvider.getParticipantUsage(instance),
usage.get(instance).intValue());
}
// update usage
String targetInstanceName = instanceNames.get(0);
int newUsgae = 12345;
capacityProvider.updateCapacity(Collections.EMPTY_MAP,
Collections.singletonMap(targetInstanceName, newUsgae), defaultCapacity);
Assert.assertEquals(capacityProvider.getParticipantUsage(targetInstanceName), newUsgae);
// check again without updating ZK
capacityProvider = new ZkBasedCapacityProvider(ZK_ADDR, CLUSTER_NAME, "Test");
Assert.assertEquals(capacityProvider.getParticipantUsage(targetInstanceName), 0);
// update with invalid value
capacityProvider.updateCapacity(Collections.EMPTY_MAP, Collections.EMPTY_MAP, -1);
try {
capacityProvider.persistCapacity();
Assert.fail("Should fail to persist invalid weight information.");
} catch (HelixException hex) {
// expected
}
}
@Test
public void testRebalanceUsingZkDataProvider() {
// capacity / weight
Map<String, Integer> capacity = new HashMap<>();
for (String instance : instanceNames) {
capacity.put(instance, defaultCapacity);
}
ZkBasedPartitionWeightProvider weightProvider =
new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
weightProvider.updateWeights(Collections.EMPTY_MAP, Collections.EMPTY_MAP, resourceWeight);
ZkBasedCapacityProvider capacityProvider =
new ZkBasedCapacityProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
capacityProvider.updateCapacity(capacity, Collections.EMPTY_MAP, 0);
TotalCapacityConstraint capacityConstraint =
new TotalCapacityConstraint(weightProvider, capacityProvider);
PartitionWeightAwareEvennessConstraint evenConstraint =
new PartitionWeightAwareEvennessConstraint(weightProvider, capacityProvider);
WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs, null,
Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
int max = Collections.max(weightCount.values());
int min = Collections.min(weightCount.values());
// Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of
// participant capacity in max.
Assert.assertTrue((max - min) <= defaultCapacity / 100);
}
@Test(dependsOnMethods = "testRebalanceUsingZkDataProvider")
public void testRebalanceWithExistingUsage() {
// capacity / weight
Map<String, Integer> capacity = new HashMap<>();
Map<String, Integer> usage = new HashMap<>();
for (int i = 0; i < instanceNames.size(); i++) {
String instance = instanceNames.get(i);
capacity.put(instance, defaultCapacity);
if (i % 7 == 0) {
usage.put(instance, defaultCapacity);
}
}
ZkBasedPartitionWeightProvider weightProvider =
new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
weightProvider.updateWeights(Collections.EMPTY_MAP, Collections.EMPTY_MAP, resourceWeight);
ZkBasedCapacityProvider capacityProvider =
new ZkBasedCapacityProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
capacityProvider.updateCapacity(capacity, usage, 0);
TotalCapacityConstraint hardConstraint =
new TotalCapacityConstraint(weightProvider, capacityProvider);
PartitionWeightAwareEvennessConstraint evenConstraint =
new PartitionWeightAwareEvennessConstraint(weightProvider, capacityProvider);
WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs, null,
Collections.<AbstractRebalanceHardConstraint> singletonList(hardConstraint),
Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
for (int i = 0; i < instanceNames.size(); i++) {
String instance = instanceNames.get(i);
if (i % 7 == 0) {
Assert.assertFalse(weightCount.containsKey(instance));
} else {
Assert.assertTrue(weightCount.get(instance) > 0);
}
}
}
@Test(dependsOnMethods = "testRebalanceUsingZkDataProvider")
public void testRebalanceOption() {
// capacity / weight
Map<String, Integer> capacity = new HashMap<>();
for (String instance : instanceNames) {
capacity.put(instance, defaultCapacity);
}
ZkBasedPartitionWeightProvider weightProvider =
new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
weightProvider.updateWeights(Collections.EMPTY_MAP, Collections.EMPTY_MAP, resourceWeight);
ZkBasedCapacityProvider capacityProvider =
new ZkBasedCapacityProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
capacityProvider.updateCapacity(capacity, Collections.EMPTY_MAP, 0);
PartitionWeightAwareEvennessConstraint evenConstraint =
new PartitionWeightAwareEvennessConstraint(weightProvider, capacityProvider);
// Assume existing assignment
ResourcesStateMap existingAssignment = new ResourcesStateMap();
String targetResource = resourceNames.get(0);
for (String partition : partitions) {
for (int i = 0; i < nReplicas; i++) {
existingAssignment.setState(targetResource, new Partition(partition), instanceNames.get(i),
topState);
}
}
WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
// INCREMENTAL
ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs,
existingAssignment, Collections.EMPTY_LIST,
Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
// check if the existingAssignment is changed
for (String partition : partitions) {
Assert.assertTrue(assignment.getInstanceStateMap(targetResource, new Partition(partition))
.keySet().containsAll(instanceNames.subList(0, nReplicas)));
}
// still need to check for balance
Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
int max = Collections.max(weightCount.values());
int min = Collections.min(weightCount.values());
// Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of
// participant capacity in max.
Assert.assertTrue((max - min) <= defaultCapacity / 100);
// FULL
assignment = util.buildFullRebalanceAssignment(resourceConfigs, existingAssignment,
Collections.EMPTY_LIST,
Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
// check if the existingAssignment is changed
for (String partition : partitions) {
Assert.assertFalse(assignment.getInstanceStateMap(targetResource, new Partition(partition))
.keySet().containsAll(instanceNames.subList(0, nReplicas)));
}
}
@Test(dependsOnMethods = "testRebalanceUsingZkDataProvider")
public void testInvalidInput() {
// capacity / weight
Map<String, Integer> capacity = new HashMap<>();
for (String instance : instanceNames) {
capacity.put(instance, defaultCapacity);
}
ZkBasedPartitionWeightProvider weightProvider =
new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
weightProvider.updateWeights(Collections.EMPTY_MAP, Collections.EMPTY_MAP, resourceWeight);
ZkBasedCapacityProvider capacityProvider =
new ZkBasedCapacityProvider(ZK_ADDR, CLUSTER_NAME, "QPS");
capacityProvider.updateCapacity(capacity, Collections.EMPTY_MAP, 0);
TotalCapacityConstraint capacityConstraint =
new TotalCapacityConstraint(weightProvider, capacityProvider);
WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
// Empty constraint
try {
util.buildIncrementalRebalanceAssignment(resourceConfigs, null, Collections.EMPTY_LIST,
Collections.EMPTY_LIST);
Assert.fail("Should fail due to empty constraint list.");
} catch (HelixException ex) {
// expected
}
ResourceConfig.Builder invalidResourceBuilder = new ResourceConfig.Builder("InvalidResource");
invalidResourceBuilder.setStateModelDefRef("OnlineOffline");
invalidResourceBuilder.setNumPartitions(nPartitions);
invalidResourceBuilder.setNumReplica(nReplicas);
for (String partition : partitions) {
invalidResourceBuilder.setPreferenceList(partition, Collections.EMPTY_LIST);
}
// Auto mode resource config
try {
invalidResourceBuilder
.setRebalanceConfig(new RebalanceConfig(new ZNRecord("InvalidResource")));
invalidResourceBuilder.getRebalanceConfig()
.setRebalanceMode(RebalanceConfig.RebalanceMode.FULL_AUTO);
util.buildIncrementalRebalanceAssignment(
Collections.singletonList(invalidResourceBuilder.build()), null,
Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
Collections.EMPTY_LIST);
Assert.fail("Should fail due to full auto resource config.");
} catch (HelixException ex) {
// expected
invalidResourceBuilder.getRebalanceConfig()
.setRebalanceMode(RebalanceConfig.RebalanceMode.CUSTOMIZED);
}
// Auto mode resource config
try {
invalidResourceBuilder.setStateModelDefRef("CustomizedOnlineOffline");
util.buildIncrementalRebalanceAssignment(
Collections.singletonList(invalidResourceBuilder.build()), null,
Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
Collections.EMPTY_LIST);
Assert.fail("Should fail due to unknown state model def ref.");
} catch (IllegalArgumentException ex) {
// expected
util.registerCustomizedStateModelDef("CustomizedOnlineOffline", OnlineOfflineSMD.build());
ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(
Collections.singletonList(invalidResourceBuilder.build()), null,
Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
Collections.EMPTY_LIST);
checkPartitionUsage(assignment, weightProvider);
}
}
}
| 9,471 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestNullReplica.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.model.IdealState;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestNullReplica extends ZkTestBase {
@Test
public void testNullReplica() 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()));
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
// set replica in ideal state to null
String idealStatePath = PropertyPathBuilder.idealState(clusterName, "TestDB0");
ZNRecord idealState = _gZkClient.readData(idealStatePath);
idealState.getSimpleFields().remove(IdealState.IdealStateProperty.REPLICAS.toString());
_gZkClient.writeData(idealStatePath, idealState);
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 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,472 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMSessionExpiry.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.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.MockParticipantManager;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestStandAloneCMSessionExpiry extends ZkTestBase {
@Test()
public void testStandAloneCMSessionExpiry() 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_PREFIX, "TestDB", 1, 20, 5, 3,
"MasterSlave", true);
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();
}
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
boolean result;
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// participant session expiry
MockParticipantManager participantToExpire = participants[1];
// System.out.println("Expire participant session");
String oldSessionId = participantToExpire.getSessionId();
ZkTestHelper.expireSession(participantToExpire.getZkClient());
String newSessionId = participantToExpire.getSessionId();
// System.out.println("oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
Assert.assertTrue(newSessionId.compareTo(oldSessionId) > 0,
"Session id should be increased after expiry");
ClusterSetup setupTool = new ClusterSetup(ZK_ADDR);
setupTool.addResourceToCluster(clusterName, "TestDB1", 10, "MasterSlave");
setupTool.rebalanceStorageCluster(clusterName, "TestDB1", 3);
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// controller session expiry
// System.out.println("Expire controller session");
oldSessionId = controller.getSessionId();
ZkTestHelper.expireSession(controller.getZkClient());
newSessionId = controller.getSessionId();
// System.out.println("oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
Assert.assertTrue(newSessionId.compareTo(oldSessionId) > 0,
"Session id should be increased after expiry");
setupTool.addResourceToCluster(clusterName, "TestDB2", 8, "MasterSlave");
setupTool.rebalanceStorageCluster(clusterName, "TestDB2", 3);
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// clean up
System.out.println("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,473 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestStartMultipleControllersWithSameName.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.ZkTestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestStartMultipleControllersWithSameName extends ZkTestBase {
@Test
public void test() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 3;
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
1, // replicas
"OnlineOffline", RebalanceMode.FULL_AUTO, true); // do
// rebalance
// start controller
ClusterControllerManager[] controllers = new ClusterControllerManager[4];
for (int i = 0; i < 4; i++) {
controllers[i] = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controllers[i].syncStart();
}
Thread.sleep(500); // wait leader election finishes
String liPath = PropertyPathBuilder.liveInstance(clusterName);
int listenerNb = ZkTestHelper.numberOfListeners(ZK_ADDR, liPath);
// System.out.println("listenerNb: " + listenerNb);
Assert.assertEquals(listenerNb, 1, "Only one controller should succeed in becoming leader");
// clean up
for (int i = 0; i < 4; i++) {
controllers[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,474 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDisableNode.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.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDisableNode extends ZkStandAloneCMTestBase {
@Test()
public void testDisableNode() throws Exception {
String command =
"-zkSvr " + ZK_ADDR + " -enableInstance " + CLUSTER_NAME + " " + PARTICIPANT_PREFIX
+ "_12918" + " TestDB TestDB_0 false";
ClusterSetup.processCommandLineArgs(command.split(" "));
boolean result =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
ZKHelixAdmin tool = new ZKHelixAdmin(_gZkClient);
tool.enableInstance(CLUSTER_NAME, PARTICIPANT_PREFIX + "_12918", true);
result =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
}
}
| 9,475 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestCMWithFailParticipant.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.common.ZkTestBase;
import org.testng.annotations.Test;
public class TestCMWithFailParticipant extends ZkTestBase {
// ZkClient _zkClient;
//
// @BeforeClass ()
// public void beforeClass() throws Exception
// {
// _zkClient = new ZkClient(ZK_ADDR);
// _zkClient.setZkSerializer(new ZNRecordSerializer());
// }
//
//
// @AfterClass
// public void afterClass()
// {
// _zkClient.close();
// }
@Test()
public void testCMWithFailParticipant() throws Exception {
int numResources = 1;
int numPartitionsPerResource = 10;
int numInstance = 5;
int replica = 3;
String uniqClusterName =
"TestFail_" + "rg" + numResources + "_p" + numPartitionsPerResource + "_n" + numInstance
+ "_r" + replica;
System.out.println("START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
TestDriver.setupCluster(uniqClusterName, ZK_ADDR, numResources, numPartitionsPerResource,
numInstance, replica);
for (int i = 0; i < numInstance; i++) {
TestDriver.startDummyParticipant(uniqClusterName, i);
}
TestDriver.startController(uniqClusterName);
TestDriver.stopDummyParticipant(uniqClusterName, 2000, 0);
TestDriver.verifyCluster(uniqClusterName, 3000, 50 * 1000);
TestDriver.stopCluster(uniqClusterName);
deleteCluster(uniqClusterName);
System.out.println("END " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,476 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestPreferenceListAsQueue.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.List;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Lists;
import org.apache.helix.AccessOption;
import org.apache.helix.HelixAdmin;
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.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.model.ClusterConstraints.ConstraintAttribute;
import org.apache.helix.model.ClusterConstraints.ConstraintType;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.IdealStateProperty;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.Message;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.model.builder.ConstraintItemBuilder;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.tools.ClusterSetup;
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.BeforeMethod;
import org.testng.annotations.Test;
public class TestPreferenceListAsQueue extends ZkUnitTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TestPreferenceListAsQueue.class);
private static final int TRANSITION_TIME = 500;
private static final int PARALLELISM = 1;
private List<String> _instanceList;
private Queue<List<String>> _prefListHistory;
private String _clusterName;
private String _stateModel;
private ClusterSetup _clusterSetup;
private HelixAdmin _admin;
private CountDownLatch _onlineLatch;
private CountDownLatch _offlineLatch;
@BeforeMethod
public void beforeMethod() {
_instanceList = Lists.newLinkedList();
_clusterSetup = new ClusterSetup(ZK_ADDR);
_admin = _clusterSetup.getClusterManagementTool();
_prefListHistory = Lists.newLinkedList();
// Create cluster
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
_clusterName = className + "_" + methodName;
_clusterSetup.addCluster(_clusterName, true);
}
@AfterClass
public void afterClass() {
deleteCluster(_clusterName);
}
/**
* This test ensures successful creation when the state model has OFFLINE --> deprioritized and
* a partition-level constraint enforces parallelism
* @throws Exception
*/
@Test
public void testReprioritizedWithConstraint() throws Exception {
_stateModel = "OnlineOfflineReprioritized";
// Add a state model with the transition to ONLINE deprioritized
_clusterSetup.addStateModelDef(_clusterName, _stateModel,
createReprioritizedStateModelDef(_stateModel));
// Add a constraint of one transition per partition
ConstraintItemBuilder constraintItemBuilder = new ConstraintItemBuilder();
constraintItemBuilder
.addConstraintAttribute(ConstraintAttribute.MESSAGE_TYPE.toString(), "STATE_TRANSITION")
.addConstraintAttribute(ConstraintAttribute.PARTITION.toString(), ".*")
.addConstraintAttribute(ConstraintAttribute.CONSTRAINT_VALUE.toString(),
String.valueOf(PARALLELISM));
_admin.setConstraint(_clusterName, ConstraintType.MESSAGE_CONSTRAINT, "constraint_1",
constraintItemBuilder.build());
runTest();
}
/**
* This test directly embeds the parallelism per partition directly into the upper bound for the
* ONLINE state. This does not require the controller to support partition-level constraints.
* @throws Exception
*/
@Test
public void testParallelismInStateModel() throws Exception {
_stateModel = "OnlineOfflineBounded";
// Add a state model with the parallelism implicit
_clusterSetup.addStateModelDef(_clusterName, _stateModel,
createEnforcedParallelismStateModelDef(_stateModel));
runTest();
}
private void runTest() throws Exception {
final int NUM_PARTITIONS = 1;
final int NUM_REPLICAS = 2;
final int NUM_INSTANCES = 2;
final String RESOURCE_NAME = "MyResource";
// Setup instances
String[] instanceInfoArray = {
"localhost_1", "localhost_2"
};
_clusterSetup.addInstancesToCluster(_clusterName, instanceInfoArray);
// Add resource
_clusterSetup.addResourceToCluster(_clusterName, RESOURCE_NAME, NUM_PARTITIONS, _stateModel,
RebalanceMode.SEMI_AUTO.toString());
// Update resource with empty preference lists
IdealState idealState = _admin.getResourceIdealState(_clusterName, RESOURCE_NAME);
for (int i = 0; i < NUM_PARTITIONS; i++) {
String partitionName = RESOURCE_NAME + "_" + i;
List<String> dummyPreferences = Lists.newArrayList();
for (int j = 0; j < NUM_REPLICAS; j++) {
// hack: need to have some dummy values in the preference list to pass validation
dummyPreferences.add("");
}
idealState.getRecord().setListField(partitionName, dummyPreferences);
}
idealState.setReplicas(String.valueOf(NUM_REPLICAS));
_admin.setResourceIdealState(_clusterName, RESOURCE_NAME, idealState);
// Start some instances
HelixManager[] participants = new HelixManager[NUM_INSTANCES];
for (int i = 0; i < NUM_INSTANCES; i++) {
participants[i] = HelixManagerFactory.getZKHelixManager(_clusterName, instanceInfoArray[i],
InstanceType.PARTICIPANT, ZK_ADDR);
participants[i].getStateMachineEngine().registerStateModelFactory(_stateModel,
new PrefListTaskOnlineOfflineStateModelFactory());
participants[i].connect();
}
// Start the controller
HelixManager controller =
HelixManagerFactory.getZKHelixManager(_clusterName, null, InstanceType.CONTROLLER, ZK_ADDR);
controller.connect();
// Disable controller immediately
_admin.enableCluster(_clusterName, false);
// This resource only has 1 partition
String partitionName = RESOURCE_NAME + "_" + 0;
// There should be no preference lists yet
Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
Arrays.asList("", "")));
// Add one instance
addInstanceToPreferences(participants[0].getHelixDataAccessor(),
participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
Arrays.asList("localhost_1", "")));
// Add a second instance immediately; the first one should still exist
addInstanceToPreferences(participants[1].getHelixDataAccessor(),
participants[1].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
Arrays.asList("localhost_1", "localhost_2")));
// Add the first instance again; it should already exist
addInstanceToPreferences(participants[0].getHelixDataAccessor(),
participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
Arrays.asList("localhost_1", "localhost_2")));
// Prepare for synchronization
_onlineLatch = new CountDownLatch(2);
_offlineLatch = new CountDownLatch(2);
_prefListHistory.clear();
// Now reenable the controller
_admin.enableCluster(_clusterName, true);
// Now wait for both instances to be done
boolean countReached = _onlineLatch.await(10000, TimeUnit.MILLISECONDS);
Assert.assertTrue(countReached);
List<String> top = _prefListHistory.poll();
assert top != null;
Assert.assertTrue(top.equals(Arrays.asList("localhost_1", ""))
|| top.equals(Arrays.asList("localhost_2", "")));
Assert.assertEquals(_prefListHistory.poll(), Arrays.asList("", ""));
// Wait for everything to be fully offline
countReached = _offlineLatch.await(10000, TimeUnit.MILLISECONDS);
Assert.assertTrue(countReached);
// Add back the instances in the opposite order
_admin.enableCluster(_clusterName, false);
addInstanceToPreferences(participants[0].getHelixDataAccessor(),
participants[1].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
addInstanceToPreferences(participants[0].getHelixDataAccessor(),
participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
Arrays.asList("localhost_2", "localhost_1")));
// Reset the latch
_onlineLatch = new CountDownLatch(2);
_prefListHistory.clear();
_admin.enableCluster(_clusterName, true);
// Now wait both to be done again
countReached = _onlineLatch.await(10000, TimeUnit.MILLISECONDS);
Assert.assertTrue(countReached);
top = _prefListHistory.poll();
assert top != null;
Assert.assertTrue(top.equals(Arrays.asList("localhost_1", ""))
|| top.equals(Arrays.asList("localhost_2", "")));
Assert.assertEquals(_prefListHistory.poll(), Arrays.asList("", ""));
Assert.assertEquals(_instanceList.size(), 0);
// Cleanup
controller.disconnect();
for (HelixManager participant : participants) {
participant.disconnect();
}
}
/**
* Create a modified version of OnlineOffline where the transition to ONLINE is given lowest
* priority
* @param stateModelName
* @return
*/
private StateModelDefinition createReprioritizedStateModelDef(String stateModelName) {
StateModelDefinition.Builder builder = new StateModelDefinition.Builder(stateModelName)
.addState("ONLINE", 1).addState("OFFLINE").addState("DROPPED").addState("ERROR")
.initialState("OFFLINE").addTransition("ERROR", "OFFLINE", 1)
.addTransition("ONLINE", "OFFLINE", 2).addTransition("OFFLINE", "DROPPED", 3)
.addTransition("OFFLINE", "ONLINE", 4).dynamicUpperBound("ONLINE", "R")
.upperBound("OFFLINE", -1).upperBound("DROPPED", -1).upperBound("ERROR", -1);
return builder.build();
}
/**
* Create a modified version of OnlineOffline where the parallelism is enforced by the upper bound
* of ONLINE
* @param stateModelName
* @return
*/
private StateModelDefinition createEnforcedParallelismStateModelDef(String stateModelName) {
StateModelDefinition.Builder builder =
new StateModelDefinition.Builder(stateModelName).addState("ONLINE", 1).addState("OFFLINE")
.addState("DROPPED").addState("ERROR").initialState("OFFLINE")
.addTransition("ERROR", "OFFLINE", 1).addTransition("ONLINE", "OFFLINE", 2)
.addTransition("OFFLINE", "DROPPED", 3).addTransition("OFFLINE", "ONLINE", 4)
.dynamicUpperBound("ONLINE", String.valueOf(PARALLELISM)).upperBound("OFFLINE", -1)
.upperBound("DROPPED", -1).upperBound("ERROR", -1);
return builder.build();
}
/**
* Check if the provided list matches the currently persisted preference list
* @param admin
* @param clusterName
* @param resourceName
* @param partitionName
* @param expectPreferenceList
* @return
*/
private boolean preferenceListIsCorrect(HelixAdmin admin, String clusterName, String resourceName,
String partitionName, List<String> expectPreferenceList) {
IdealState idealState = admin.getResourceIdealState(clusterName, resourceName);
List<String> preferenceList = idealState.getPreferenceList(partitionName);
return expectPreferenceList.equals(preferenceList);
}
/**
* Update an ideal state so that partitions will have an instance removed from their preference
* lists
* @param accessor
* @param instanceName
* @param resourceName
* @param partitionName
*/
private void removeInstanceFromPreferences(HelixDataAccessor accessor, final String instanceName,
final String resourceName, final String partitionName) {
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
String idealStatePath = keyBuilder.idealStates(resourceName).getPath();
synchronized (_prefListHistory) {
// Updater for ideal state
final List<String> prefList = Lists.newLinkedList();
DataUpdater<ZNRecord> idealStateUpdater = currentData -> {
List<String> preferenceList = currentData.getListField(partitionName);
int numReplicas =
Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
List<String> newPrefList =
removeInstanceFromPreferenceList(preferenceList, instanceName, numReplicas);
currentData.setListField(partitionName, newPrefList);
prefList.clear();
prefList.addAll(newPrefList);
return currentData;
};
List<DataUpdater<ZNRecord>> updaters = Lists.newArrayList();
updaters.add(idealStateUpdater);
accessor.updateChildren(Collections.singletonList(idealStatePath), updaters,
AccessOption.PERSISTENT);
_prefListHistory.add(prefList);
}
}
/**
* Update an ideal state so that partitions will have a new instance at the tails of their
* preference lists
* @param accessor
* @param instanceName
* @param resourceName
* @param partitions
*/
private void addInstanceToPreferences(HelixDataAccessor accessor, final String instanceName,
final String resourceName, final List<String> partitions) {
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
String idealStatePath = keyBuilder.idealStates(resourceName).getPath();
synchronized (_prefListHistory) {
// Updater for ideal state
final List<String> prefList = Lists.newLinkedList();
DataUpdater<ZNRecord> idealStateUpdater = currentData -> {
for (String partitionName : partitions) {
List<String> preferenceList = currentData.getListField(partitionName);
int numReplicas =
Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
List<String> newPrefList =
addInstanceToPreferenceList(preferenceList, instanceName, numReplicas);
currentData.setListField(partitionName, newPrefList);
prefList.clear();
prefList.addAll(newPrefList);
}
return currentData;
};
// Send update requests together
List<DataUpdater<ZNRecord>> updaters = Lists.newArrayList();
updaters.add(idealStateUpdater);
accessor.updateChildren(Collections.singletonList(idealStatePath), updaters,
AccessOption.PERSISTENT);
_prefListHistory.add(prefList);
}
}
/**
* Add the instance to the preference list, removing padding as necessary
* @param existPreferences
* @param instanceName
* @param numReplicas
* @return A new preference list with the instance added to the end (if it did not already exist)
*/
private static List<String> addInstanceToPreferenceList(List<String> existPreferences,
String instanceName, int numReplicas) {
if (existPreferences == null) {
existPreferences = Lists.newArrayList();
}
List<String> newPreferences = Lists.newArrayListWithCapacity(numReplicas);
for (String existInstance : existPreferences) {
if (!existInstance.isEmpty()) {
newPreferences.add(existInstance);
}
}
if (!newPreferences.contains(instanceName)) {
newPreferences.add(instanceName);
}
addDummiesToPreferenceList(newPreferences, numReplicas);
return newPreferences;
}
/**
* Remove an instance from a preference list, padding as necessary
* @param existPreferences
* @param instanceName
* @param numReplicas
* @return new preference list with the instance removed (if it existed)
*/
private static List<String> removeInstanceFromPreferenceList(List<String> existPreferences,
String instanceName, int numReplicas) {
if (existPreferences == null) {
existPreferences = Lists.newArrayList();
}
List<String> newPreferences = Lists.newArrayListWithCapacity(numReplicas);
for (String existInstance : existPreferences) {
if (!existInstance.isEmpty() && !existInstance.equals(instanceName)) {
newPreferences.add(existInstance);
}
}
addDummiesToPreferenceList(newPreferences, numReplicas);
return newPreferences;
}
/**
* Pad a preference list with empty strings to have it reach numReplicas size
* @param preferences
* @param numReplicas
*/
private static void addDummiesToPreferenceList(List<String> preferences, int numReplicas) {
int numRemaining = numReplicas - preferences.size();
numRemaining = (numRemaining > 0) ? numRemaining : 0;
for (int i = 0; i < numRemaining; i++) {
preferences.add("");
}
}
/**
* A state model whose callbacks correspond to when to run a task. When becoming online, the task
* should be run, and then the instance should be removed from the preference list for the task
* (padded by spaces). All other transitions are no-ops.
*/
public class PrefListTaskOnlineOfflineStateModel extends StateModel {
/**
* Run the task. The parallelism of this is dictated by the constraints that are set.
* @param message
* @param context
* @throws InterruptedException
*/
public void onBecomeOnlineFromOffline(final Message message, NotificationContext context)
throws InterruptedException {
// Do the work, and then finally remove the instance from the preference list for this
// partition
HelixManager manager = context.getManager();
LOG.info("START onBecomeOnlineFromOffline for " + message.getPartitionName() + " on "
+ manager.getInstanceName());
int oldSize;
synchronized (_instanceList) {
oldSize = _instanceList.size();
_instanceList.add(manager.getInstanceName());
}
Assert.assertEquals(oldSize, 0); // ensure these transitions are fully synchronized
Thread.sleep(TRANSITION_TIME); // a sleep simulates work
// Need to disable in order to get the transition the next time
HelixDataAccessor accessor = manager.getHelixDataAccessor();
removeInstanceFromPreferences(accessor, manager.getInstanceName(), message.getResourceName(),
message.getPartitionName());
LOG.info("FINISH onBecomeOnlineFromOffline for " + message.getPartitionName() + " on "
+ manager.getInstanceName());
int newSize;
synchronized (_instanceList) {
_instanceList.remove(_instanceList.size() - 1);
newSize = _instanceList.size();
}
Assert.assertEquals(newSize, oldSize); // ensure nothing came in during this time
_onlineLatch.countDown();
}
public void onBecomeOfflineFromOnline(Message message, NotificationContext context) {
HelixManager manager = context.getManager();
LOG.info("onBecomeOfflineFromOnline for " + message.getPartitionName() + " on "
+ manager.getInstanceName());
}
public void onBecomeDroppedFromOffline(Message message, NotificationContext context) {
HelixManager manager = context.getManager();
LOG.info("onBecomeDroppedFromOffline for " + message.getPartitionName() + " on "
+ manager.getInstanceName());
_offlineLatch.countDown();
}
public void onBecomeOfflineFromError(Message message, NotificationContext context) {
HelixManager manager = context.getManager();
LOG.info("onBecomeOfflineFromError for " + message.getPartitionName() + " on "
+ manager.getInstanceName());
}
}
public class PrefListTaskOnlineOfflineStateModelFactory
extends StateModelFactory<PrefListTaskOnlineOfflineStateModel> {
@Override
public PrefListTaskOnlineOfflineStateModel createNewStateModel(String resource,
String partitionName) {
return new PrefListTaskOnlineOfflineStateModel();
}
}
}
| 9,477 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestSchemataSM.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.Collections;
import java.util.Date;
import java.util.Map;
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.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestSchemataSM extends ZkTestBase {
@Test
public void testSchemataSM() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 5;
MockParticipantManager[] participants = new MockParticipantManager[n];
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant start port
"localhost", // participant name prefix
"TestSchemata", // resource name prefix
1, // resources
1, // partitions per resource
n, // number of nodes
0, // replicas
"STORAGE_DEFAULT_SM_SCHEMATA", false); // don't rebalance
// rebalance ideal-state to use ANY_LIVEINSTANCE for preference list
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
PropertyKey key = keyBuilder.idealStates("TestSchemata0");
IdealState idealState = accessor.getProperty(key);
idealState.setReplicas(IdealState.IdealStateConstants.ANY_LIVEINSTANCE.toString());
idealState.getRecord().setListField("TestSchemata0_0",
Collections.singletonList(IdealState.IdealStateConstants.ANY_LIVEINSTANCE.toString()));
accessor.setProperty(key, idealState);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start n-1 participants
for (int i = 1; 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);
// start the remaining 1 participant
participants[0] = new MockParticipantManager(ZK_ADDR, clusterName, "localhost_12918");
participants[0].syncStart();
// make sure we have all participants in MASTER state
result = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
key = keyBuilder.externalView("TestSchemata0");
ExternalView externalView = accessor.getProperty(key);
Map<String, String> stateMap = externalView.getStateMap("TestSchemata0_0");
Assert.assertNotNull(stateMap);
Assert.assertEquals(stateMap.size(), n, "all " + n + " participants should be in Master state");
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
Assert.assertNotNull(stateMap.get(instanceName));
Assert.assertEquals(stateMap.get(instanceName), "MASTER");
}
// 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,478 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDistributedClusterController.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.HashSet;
import java.util.Set;
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.ClusterDistributedController;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDistributedClusterController extends ZkTestBase {
@Test
public void testDistributedClusterController() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterNamePrefix = className + "_" + methodName;
final int n = 5;
final int clusterNb = 10;
Set<MockParticipantManager> participantRefs = new HashSet<>();
System.out
.println("START " + clusterNamePrefix + " at " + new Date(System.currentTimeMillis()));
// setup 10 clusters
for (int i = 0; i < clusterNb; i++) {
String clusterName = clusterNamePrefix + "0_" + i;
String participantName = "localhost" + i;
String resourceName = "TestDB" + i;
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
participantName, // participant name prefix
resourceName, // resource name prefix
1, // resources
8, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
}
// setup controller cluster
final String controllerClusterName = "CONTROLLER_" + clusterNamePrefix;
TestHelper.setupCluster("CONTROLLER_" + clusterNamePrefix, ZK_ADDR, 0, // controller
// port
"controller", // participant name prefix
clusterNamePrefix, // resource name prefix
1, // resources
clusterNb, // partitions per resource
n, // number of nodes
3, // replicas
"LeaderStandby", true); // do rebalance
// start distributed cluster controllers
ClusterDistributedController[] controllers = new ClusterDistributedController[n];
for (int i = 0; i < n; i++) {
controllers[i] =
new ClusterDistributedController(ZK_ADDR, controllerClusterName, "controller_" + i);
controllers[i].syncStart();
}
boolean result = ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, controllerClusterName),
30000);
Assert.assertTrue(result, "Controller cluster NOT in ideal state");
// start first cluster
MockParticipantManager[] participants = new MockParticipantManager[n];
final String firstClusterName = clusterNamePrefix + "0_0";
for (int i = 0; i < n; i++) {
String instanceName = "localhost0_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, firstClusterName, instanceName);
participants[i].syncStart();
participantRefs.add(participants[i]);
}
result = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, firstClusterName));
Assert.assertTrue(result, "first cluster NOT in ideal state");
// stop current leader in controller cluster
ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(controllerClusterName, baseAccessor);
Builder keyBuilder = accessor.keyBuilder();
LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
String leaderName = leader.getId();
int j = Integer.parseInt(leaderName.substring(leaderName.lastIndexOf('_') + 1));
controllers[j].syncStop();
// setup the second cluster
MockParticipantManager[] participants2 = new MockParticipantManager[n];
final String secondClusterName = clusterNamePrefix + "0_1";
for (int i = 0; i < n; i++) {
String instanceName = "localhost1_" + (12918 + i);
participants2[i] = new MockParticipantManager(ZK_ADDR, secondClusterName, instanceName);
participants2[i].syncStart();
participantRefs.add(participants2[i]);
}
result = ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, secondClusterName));
Assert.assertTrue(result, "second cluster NOT in ideal state");
// clean up
// wait for all zk callbacks done
System.out.println("Cleaning up...");
for (int i = 0; i < 5; i++) {
Assert.assertTrue(ClusterStateVerifier
.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, controllerClusterName)));
controllers[i].syncStop();
}
for (MockParticipantManager participant : participantRefs) {
participant.syncStop();
}
// delete 10 clusters
for (int i = 0; i < clusterNb; i++) {
deleteCluster(clusterNamePrefix + "0_" + i);
}
deleteCluster(controllerClusterName);
}
}
| 9,479 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestHelixCloudProperty.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.Collections;
import org.apache.helix.HelixCloudProperty;
import org.apache.helix.cloud.constants.CloudProvider;
import org.apache.helix.model.CloudConfig;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestHelixCloudProperty {
@Test
public void testHelixCloudPropertyAzure() {
CloudConfig azureCloudConfig =
new CloudConfig.Builder().setCloudEnabled(true).setCloudID("AzureTestId1")
.setCloudProvider(CloudProvider.AZURE).build();
HelixCloudProperty azureCloudProperty = new HelixCloudProperty(azureCloudConfig);
Assert.assertTrue(azureCloudProperty.getCloudEnabled());
Assert.assertEquals(azureCloudProperty.getCloudId(), "AzureTestId1");
Assert.assertEquals(azureCloudProperty.getCloudProvider(), CloudProvider.AZURE.name());
Assert.assertEquals(azureCloudProperty.getCloudInfoSources(), Collections.singletonList(
"http://169.254.169.254/metadata/instance?api-version=2019-06-04"));
Assert.assertEquals(azureCloudProperty.getCloudMaxRetry(), 5);
Assert.assertEquals(azureCloudProperty.getCloudConnectionTimeout(), 5000);
Assert.assertEquals(azureCloudProperty.getCloudRequestTimeout(), 5000);
Assert.assertEquals(azureCloudProperty.getCloudInfoProcessorPackage(),
"org.apache.helix.cloud.azure");
Assert.assertEquals(azureCloudProperty.getCloudInfoProcessorName(),
"AzureCloudInstanceInformationProcessor");
Assert.assertEquals(azureCloudProperty.getCloudInfoProcessorFullyQualifiedClassName(),
"org.apache.helix.cloud.azure.AzureCloudInstanceInformationProcessor");
}
@Test
public void testHelixCloudPropertyCustomizedFullyQualified() {
CloudConfig customCloudConfig =
new CloudConfig.Builder().setCloudEnabled(true).setCloudProvider(CloudProvider.CUSTOMIZED)
.setCloudInfoProcessorPackageName("org.apache.foo.bar")
.setCloudInfoProcessorName("CustomCloudInstanceInfoProcessor")
.setCloudInfoSources(Collections.singletonList("https://custom-cloud.com")).build();
HelixCloudProperty customCloudProperty = new HelixCloudProperty(customCloudConfig);
Assert.assertTrue(customCloudProperty.getCloudEnabled());
Assert.assertEquals(customCloudProperty.getCloudProvider(), CloudProvider.CUSTOMIZED.name());
Assert.assertEquals(customCloudProperty.getCloudInfoSources(),
Collections.singletonList("https://custom-cloud.com"));
Assert.assertEquals(customCloudProperty.getCloudInfoProcessorPackage(), "org.apache.foo.bar");
Assert.assertEquals(customCloudProperty.getCloudInfoProcessorName(),
"CustomCloudInstanceInfoProcessor");
Assert.assertEquals(customCloudProperty.getCloudInfoProcessorFullyQualifiedClassName(),
"org.apache.foo.bar.CustomCloudInstanceInfoProcessor");
}
@Test
public void testHelixCloudPropertyClassNameOnly() {
CloudConfig customCloudConfig =
new CloudConfig.Builder().setCloudEnabled(true).setCloudProvider(CloudProvider.CUSTOMIZED)
.setCloudInfoProcessorName("CustomCloudInstanceInfoProcessor")
.setCloudInfoSources(Collections.singletonList("https://custom-cloud.com")).build();
HelixCloudProperty customCloudProperty = new HelixCloudProperty(customCloudConfig);
Assert.assertTrue(customCloudProperty.getCloudEnabled());
Assert.assertEquals(customCloudProperty.getCloudProvider(), CloudProvider.CUSTOMIZED.name());
Assert.assertEquals(customCloudProperty.getCloudInfoSources(),
Collections.singletonList("https://custom-cloud.com"));
Assert.assertEquals(customCloudProperty.getCloudInfoProcessorPackage(),
"org.apache.helix.cloud.customized");
Assert.assertEquals(customCloudProperty.getCloudInfoProcessorName(),
"CustomCloudInstanceInfoProcessor");
Assert.assertEquals(customCloudProperty.getCloudInfoProcessorFullyQualifiedClassName(),
"org.apache.helix.cloud.customized.CustomCloudInstanceInfoProcessor");
}
}
| 9,480 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDriver.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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.helix.HelixManager;
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.manager.zk.ZNRecordSerializer;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory;
import org.apache.helix.model.IdealState.IdealStateProperty;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.store.PropertyJsonSerializer;
import org.apache.helix.store.PropertyStoreException;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.apache.helix.tools.DefaultIdealStateCalculator;
import org.apache.helix.tools.TestCommand;
import org.apache.helix.tools.TestCommand.CommandType;
import org.apache.helix.tools.TestExecutor;
import org.apache.helix.tools.TestExecutor.ZnodePropertyType;
import org.apache.helix.tools.TestTrigger;
import org.apache.helix.tools.ZnodeOpArg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
public class TestDriver {
private static Logger LOG = LoggerFactory.getLogger(TestDriver.class);
private static final String ZK_ADDR = ZkTestBase.ZK_ADDR;
// private static final String CLUSTER_PREFIX = "TestDriver";
private static final String STATE_MODEL = "MasterSlave";
private static final String TEST_DB_PREFIX = "TestDB";
private static final int START_PORT = 12918;
private static final String CONTROLLER_PREFIX = "controller";
private static final String PARTICIPANT_PREFIX = "localhost";
private static final Random RANDOM = new Random();
private static final PropertyJsonSerializer<ZNRecord> SERIALIZER =
new PropertyJsonSerializer<ZNRecord>(ZNRecord.class);
private static final Map<String, TestInfo> _testInfoMap =
new ConcurrentHashMap<String, TestInfo>();
public static class TestInfo {
public final HelixZkClient _zkClient;
public final String _clusterName;
public final int _numDb;
public final int _numPartitionsPerDb;
public final int _numNode;
public final int _replica;
public final Map<String, HelixManager> _managers =
new ConcurrentHashMap<String, HelixManager>();
public TestInfo(String clusterName, HelixZkClient zkClient, int numDb, int numPartitionsPerDb,
int numNode, int replica) {
this._clusterName = clusterName;
this._zkClient = zkClient;
this._numDb = numDb;
this._numPartitionsPerDb = numPartitionsPerDb;
this._numNode = numNode;
this._replica = replica;
}
}
public static TestInfo getTestInfo(String uniqClusterName) {
if (!_testInfoMap.containsKey(uniqClusterName)) {
String errMsg = "Cluster hasn't been setup for " + uniqClusterName;
throw new IllegalArgumentException(errMsg);
}
TestInfo testInfo = _testInfoMap.get(uniqClusterName);
return testInfo;
}
public static void setupClusterWithoutRebalance(String uniqClusterName, String zkAddr,
int numResources, int numPartitionsPerResource, int numInstances, int replica)
throws Exception {
setupCluster(uniqClusterName, zkAddr, numResources, numPartitionsPerResource, numInstances,
replica, false);
}
public static void setupCluster(String uniqClusterName, String zkAddr, int numResources,
int numPartitionsPerResource, int numInstances, int replica) throws Exception {
setupCluster(uniqClusterName, zkAddr, numResources, numPartitionsPerResource, numInstances,
replica, true);
}
public static void setupCluster(String uniqClusterName, String zkAddr, int numResources,
int numPartitionsPerResource, int numInstances, int replica, boolean doRebalance)
throws Exception {
HelixZkClient zkClient = SharedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(ZK_ADDR));
try {
zkClient.setZkSerializer(new ZNRecordSerializer());
// String clusterName = CLUSTER_PREFIX + "_" + uniqClusterName;
String clusterName = uniqClusterName;
if (zkClient.exists("/" + clusterName)) {
LOG.warn("test cluster already exists:" + clusterName + ", test name:" + uniqClusterName + " is not unique or test has been run without cleaning up zk; deleting it");
zkClient.deleteRecursively("/" + clusterName);
}
if (_testInfoMap.containsKey(uniqClusterName)) {
LOG.warn("test info already exists:" + uniqClusterName + " is not unique or test has been run without cleaning up test info map; removing it");
_testInfoMap.remove(uniqClusterName);
}
TestInfo testInfo =
new TestInfo(clusterName, zkClient, numResources, numPartitionsPerResource, numInstances,
replica);
_testInfoMap.put(uniqClusterName, testInfo);
ClusterSetup setupTool = new ClusterSetup(zkAddr);
setupTool.addCluster(clusterName, true);
for (int i = 0; i < numInstances; i++) {
int port = START_PORT + i;
setupTool.addInstanceToCluster(clusterName, PARTICIPANT_PREFIX + "_" + port);
}
for (int i = 0; i < numResources; i++) {
String dbName = TEST_DB_PREFIX + i;
setupTool.addResourceToCluster(clusterName, dbName, numPartitionsPerResource, STATE_MODEL);
if (doRebalance) {
setupTool.rebalanceStorageCluster(clusterName, dbName, replica);
// String idealStatePath = "/" + clusterName + "/" +
// PropertyType.IDEALSTATES.toString() + "/"
// + dbName;
// ZNRecord idealState = zkClient.<ZNRecord> readData(idealStatePath);
// testInfo._idealStateMap.put(dbName, idealState);
}
}
} finally {
zkClient.close();
}
}
/**
* starting a dummy participant with a given id
* @param uniqClusterName
* @param instanceId
*/
public static void startDummyParticipant(String uniqClusterName, int instanceId) throws Exception {
startDummyParticipants(uniqClusterName, new int[] {
instanceId
});
}
public static void startDummyParticipants(String uniqClusterName, int[] instanceIds)
throws Exception {
if (!_testInfoMap.containsKey(uniqClusterName)) {
String errMsg = "test cluster hasn't been setup:" + uniqClusterName;
throw new IllegalArgumentException(errMsg);
}
TestInfo testInfo = _testInfoMap.get(uniqClusterName);
String clusterName = testInfo._clusterName;
for (int id : instanceIds) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + id);
// if (testInfo._startCMResultMap.containsKey(instanceName)) {
if (testInfo._managers.containsKey(instanceName)) {
LOG.warn("Dummy participant:" + instanceName + " has already started; skip starting it");
} else {
// StartCMResult result = TestHelper.startDummyProcess(ZK_ADDR, clusterName, instanceName);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participant.syncStart();
testInfo._managers.put(instanceName, participant);
// testInfo._instanceStarted.countDown();
}
}
}
public static void startController(String uniqClusterName) throws Exception {
startController(uniqClusterName, new int[] {
0
});
}
public static void startController(String uniqClusterName, int[] nodeIds) throws Exception {
if (!_testInfoMap.containsKey(uniqClusterName)) {
String errMsg = "test cluster hasn't been setup:" + uniqClusterName;
throw new IllegalArgumentException(errMsg);
}
TestInfo testInfo = _testInfoMap.get(uniqClusterName);
String clusterName = testInfo._clusterName;
for (int id : nodeIds) {
String controllerName = CONTROLLER_PREFIX + "_" + id;
if (testInfo._managers.containsKey(controllerName)) {
LOG.warn("Controller:" + controllerName + " has already started; skip starting it");
} else {
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, controllerName);
controller.syncStart();
testInfo._managers.put(controllerName, controller);
}
}
}
public static void verifyCluster(String uniqClusterName, long beginTime, long timeout)
throws Exception {
Thread.sleep(beginTime);
if (!_testInfoMap.containsKey(uniqClusterName)) {
String errMsg = "test cluster hasn't been setup:" + uniqClusterName;
throw new IllegalArgumentException(errMsg);
}
TestInfo testInfo = _testInfoMap.get(uniqClusterName);
String clusterName = testInfo._clusterName;
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkAddr(ZK_ADDR)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(verifier.verifyByPolling());
} finally {
verifier.close();
}
}
public static void stopCluster(String uniqClusterName) throws Exception {
if (!_testInfoMap.containsKey(uniqClusterName)) {
String errMsg = "test cluster hasn't been setup:" + uniqClusterName;
throw new IllegalArgumentException(errMsg);
}
TestInfo testInfo = _testInfoMap.remove(uniqClusterName);
// stop controller first
for (String instanceName : testInfo._managers.keySet()) {
if (instanceName.startsWith(CONTROLLER_PREFIX)) {
ClusterControllerManager controller =
(ClusterControllerManager) testInfo._managers.get(instanceName);
controller.syncStop();
}
}
Thread.sleep(1000);
for (String instanceName : testInfo._managers.keySet()) {
if (!instanceName.startsWith(CONTROLLER_PREFIX)) {
MockParticipantManager participant =
(MockParticipantManager) testInfo._managers.get(instanceName);
participant.syncStop();
}
}
testInfo._zkClient.close();
}
public static void stopDummyParticipant(String uniqClusterName, long beginTime, int instanceId)
throws Exception {
if (!_testInfoMap.containsKey(uniqClusterName)) {
String errMsg = "test cluster hasn't been setup:" + uniqClusterName;
throw new Exception(errMsg);
}
TestInfo testInfo = _testInfoMap.get(uniqClusterName);
String failHost = PARTICIPANT_PREFIX + "_" + (START_PORT + instanceId);
MockParticipantManager participant =
(MockParticipantManager) testInfo._managers.remove(failHost);
// TODO need sync
if (participant == null) {
String errMsg = "Dummy participant:" + failHost + " seems not running";
LOG.error(errMsg);
} else {
// System.err.println("try to stop participant: " +
// result._manager.getInstanceName());
// NodeOpArg arg = new NodeOpArg(result._manager, result._thread);
// TestCommand command = new TestCommand(CommandType.STOP, new TestTrigger(beginTime), arg);
// List<TestCommand> commandList = new ArrayList<TestCommand>();
// commandList.add(command);
// TestExecutor.executeTestAsync(commandList, ZK_ADDR);
participant.syncStop();
}
}
public static void setIdealState(String uniqClusterName, long beginTime, int percentage)
throws Exception {
if (!_testInfoMap.containsKey(uniqClusterName)) {
String errMsg = "test cluster hasn't been setup:" + uniqClusterName;
throw new IllegalArgumentException(errMsg);
}
TestInfo testInfo = _testInfoMap.get(uniqClusterName);
String clusterName = testInfo._clusterName;
List<String> instanceNames = new ArrayList<String>();
for (int i = 0; i < testInfo._numNode; i++) {
int port = START_PORT + i;
instanceNames.add(PARTICIPANT_PREFIX + "_" + port);
}
List<TestCommand> commandList = new ArrayList<TestCommand>();
for (int i = 0; i < testInfo._numDb; i++) {
String dbName = TEST_DB_PREFIX + i;
ZNRecord destIS =
DefaultIdealStateCalculator.calculateIdealState(instanceNames,
testInfo._numPartitionsPerDb, testInfo._replica - 1, dbName, "MASTER", "SLAVE");
// destIS.setId(dbName);
destIS.setSimpleField(IdealStateProperty.REBALANCE_MODE.toString(),
RebalanceMode.CUSTOMIZED.toString());
destIS.setSimpleField(IdealStateProperty.NUM_PARTITIONS.toString(),
Integer.toString(testInfo._numPartitionsPerDb));
destIS.setSimpleField(IdealStateProperty.STATE_MODEL_DEF_REF.toString(), STATE_MODEL);
destIS.setSimpleField(IdealStateProperty.REPLICAS.toString(), "" + testInfo._replica);
// String idealStatePath = "/" + clusterName + "/" +
// PropertyType.IDEALSTATES.toString() + "/"
// + TEST_DB_PREFIX + i;
ZNRecord initIS = new ZNRecord(dbName); // _zkClient.<ZNRecord>
// readData(idealStatePath);
initIS.setSimpleField(IdealStateProperty.REBALANCE_MODE.toString(),
RebalanceMode.CUSTOMIZED.toString());
initIS.setSimpleField(IdealStateProperty.NUM_PARTITIONS.toString(),
Integer.toString(testInfo._numPartitionsPerDb));
initIS.setSimpleField(IdealStateProperty.STATE_MODEL_DEF_REF.toString(), STATE_MODEL);
initIS.setSimpleField(IdealStateProperty.REPLICAS.toString(), "" + testInfo._replica);
int totalStep = calcuateNumTransitions(initIS, destIS);
// LOG.info("initIS:" + initIS);
// LOG.info("destIS:" + destIS);
// LOG.info("totalSteps from initIS to destIS:" + totalStep);
// System.out.println("initIS:" + initIS);
// System.out.println("destIS:" + destIS);
ZNRecord nextIS;
int step = totalStep * percentage / 100;
System.out.println("Resource:" + dbName + ", totalSteps from initIS to destIS:" + totalStep
+ ", walk " + step + " steps(" + percentage + "%)");
nextIS = nextIdealState(initIS, destIS, step);
// testInfo._idealStateMap.put(dbName, nextIS);
String idealStatePath = PropertyPathBuilder.idealState(clusterName, TEST_DB_PREFIX + i);
ZnodeOpArg arg = new ZnodeOpArg(idealStatePath, ZnodePropertyType.ZNODE, "+", nextIS);
TestCommand command = new TestCommand(CommandType.MODIFY, new TestTrigger(beginTime), arg);
commandList.add(command);
}
TestExecutor.executeTestAsync(commandList, ZK_ADDR);
}
private static List<String[]> findAllUnfinishPairs(ZNRecord cur, ZNRecord dest) {
// find all (host, resource) pairs that haven't reached destination state
List<String[]> list = new ArrayList<String[]>();
Map<String, Map<String, String>> map = dest.getMapFields();
for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) {
String partitionName = entry.getKey();
Map<String, String> hostMap = entry.getValue();
for (Map.Entry<String, String> hostEntry : hostMap.entrySet()) {
String host = hostEntry.getKey();
String destState = hostEntry.getValue();
Map<String, String> curHostMap = cur.getMapField(partitionName);
String curState = null;
if (curHostMap != null) {
curState = curHostMap.get(host);
}
String[] pair = new String[3];
if (curState == null) {
if (destState.equalsIgnoreCase("SLAVE")) {
pair[0] = new String(partitionName);
pair[1] = new String(host);
pair[2] = new String("1"); // number of transitions required
list.add(pair);
} else if (destState.equalsIgnoreCase("MASTER")) {
pair[0] = new String(partitionName);
pair[1] = new String(host);
pair[2] = new String("2"); // number of transitions required
list.add(pair);
}
} else {
if (curState.equalsIgnoreCase("SLAVE") && destState.equalsIgnoreCase("MASTER")) {
pair[0] = new String(partitionName);
pair[1] = new String(host);
pair[2] = new String("1"); // number of transitions required
list.add(pair);
}
}
}
}
return list;
}
private static int calcuateNumTransitions(ZNRecord start, ZNRecord end) {
int totalSteps = 0;
List<String[]> list = findAllUnfinishPairs(start, end);
for (String[] pair : list) {
totalSteps += Integer.parseInt(pair[2]);
}
return totalSteps;
}
private static ZNRecord nextIdealState(final ZNRecord cur, final ZNRecord dest, final int steps)
throws PropertyStoreException {
// get a deep copy
ZNRecord next = SERIALIZER.deserialize(SERIALIZER.serialize(cur));
List<String[]> list = findAllUnfinishPairs(cur, dest);
// randomly pick up pairs that haven't reached destination state and
// progress
for (int i = 0; i < steps; i++) {
int randomInt = RANDOM.nextInt(list.size());
String[] pair = list.get(randomInt);
String curState = null;
Map<String, String> curHostMap = next.getMapField(pair[0]);
if (curHostMap != null) {
curState = curHostMap.get(pair[1]);
}
final String destState = dest.getMapField(pair[0]).get(pair[1]);
// TODO generalize it using state-model
if (curState == null && destState != null) {
Map<String, String> hostMap = next.getMapField(pair[0]);
if (hostMap == null) {
hostMap = new HashMap<String, String>();
}
hostMap.put(pair[1], "SLAVE");
next.setMapField(pair[0], hostMap);
} else if (curState.equalsIgnoreCase("SLAVE") && destState != null
&& destState.equalsIgnoreCase("MASTER")) {
next.getMapField(pair[0]).put(pair[1], "MASTER");
} else {
LOG.error("fail to calculate the next ideal state");
}
curState = next.getMapField(pair[0]).get(pair[1]);
if (curState != null && curState.equalsIgnoreCase(destState)) {
list.remove(randomInt);
}
}
LOG.info("nextIS:" + next);
return next;
}
}
| 9,481 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestStateTransitionThrottle.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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.api.config.StateTransitionThrottleConfig;
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.mock.participant.ErrTransition;
import org.apache.helix.mock.participant.SleepTransition;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestStateTransitionThrottle extends ZkTestBase {
private int participantCount = 4;
String resourceName = "TestDB0";
@Test
public void testTransitionThrottleOnRecoveryPartition() throws Exception {
String clusterName = getShortClassName() + "testRecoveryPartition";
MockParticipantManager[] participants = new MockParticipantManager[participantCount];
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
final ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
setupCluster(clusterName, accessor);
// start partial participants
for (int i = 0; i < participantCount - 1; i++) {
participants[i] =
new MockParticipantManager(ZK_ADDR, clusterName, "localhost_" + (12918 + i));
if (i == 0) {
// One participant 0, delay processing partition 0 transition
final String delayedPartitionName = resourceName + "_0";
participants[i].setTransition(new SleepTransition(99999999) {
@Override
public void doTransition(Message message, NotificationContext context)
throws InterruptedException {
String partition = message.getPartitionName();
if (partition.equals(delayedPartitionName)) {
super.doTransition(message, context);
}
}
});
}
participants[i].syncStart();
}
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();
// Won't match, since there is pending transition
Assert.assertFalse(verifier.verify(3000));
participants[participantCount - 1] = new MockParticipantManager(ZK_ADDR, clusterName,
"localhost_" + (12918 + participantCount - 1));
participants[participantCount - 1].syncStart();
// Load balance transition (downward) will be scheduled even though there is pending recovery
// balance transition
Assert.assertTrue(pollForPartitionAssignment(accessor, participants[participantCount - 1],
resourceName, 5000));
// Stop participant, so blocking transition is removed.
participants[0].syncStop();
Assert.assertTrue(pollForPartitionAssignment(accessor, participants[participantCount - 1],
resourceName, 5000));
// clean up
controller.syncStop();
for (int i = 0; i < participantCount; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testTransitionThrottleOnErrorPartition() throws Exception {
String clusterName = getShortClassName() + "testMaxErrorPartition";
MockParticipantManager[] participants = new MockParticipantManager[participantCount];
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
final ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
setupCluster(clusterName, accessor);
// Set throttle config to enable throttling
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ClusterConfig clusterConfig = accessor.getProperty(accessor.keyBuilder().clusterConfig());
clusterConfig.setResourcePriorityField("Name");
List<StateTransitionThrottleConfig> throttleConfigs = new ArrayList<>();
throttleConfigs.add(
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 100));
throttleConfigs.add(new StateTransitionThrottleConfig(
StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 100));
clusterConfig.setStateTransitionThrottleConfigs(throttleConfigs);
accessor.setProperty(keyBuilder.clusterConfig(), clusterConfig);
// set one partition to be always Error, so load balance won't be triggered
Map<String, Set<String>> errPartitions = new HashMap<>();
errPartitions.put("OFFLINE-SLAVE", TestHelper.setOf(resourceName + "_0"));
// start part of participants
for (int i = 0; i < participantCount - 1; i++) {
participants[i] =
new MockParticipantManager(ZK_ADDR, clusterName, "localhost_" + (12918 + i));
if (i == 0) {
participants[i].setTransition(new ErrTransition(errPartitions));
}
participants[i].syncStart();
}
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();
Assert.assertTrue(verifier.verify(3000));
// Adding one more participant.
participants[participantCount - 1] = new MockParticipantManager(ZK_ADDR, clusterName,
"localhost_" + (12918 + participantCount - 1));
participants[participantCount - 1].syncStart();
// Even though there is an error partition, downward load balance will take place
Assert.assertTrue(pollForPartitionAssignment(accessor, participants[participantCount - 1],
resourceName, 5000));
// Update cluster config to tolerate error partition, so load balance transition will be done
clusterConfig = accessor.getProperty(accessor.keyBuilder().clusterConfig());
clusterConfig.setErrorPartitionThresholdForLoadBalance(1);
accessor.setProperty(keyBuilder.clusterConfig(), clusterConfig);
_gSetupTool.rebalanceResource(clusterName, resourceName, 3);
Assert.assertTrue(pollForPartitionAssignment(accessor, participants[participantCount - 1],
resourceName, 3000));
// clean up
controller.syncStop();
for (int i = 0; i < participantCount; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
private void setupCluster(String clusterName, ZKHelixDataAccessor accessor) throws Exception {
String resourceNamePrefix = "TestDB";
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant start port
"localhost", // participant name prefix
resourceNamePrefix, // resource name prefix
1, // resources
15, // partitions per resource
participantCount, // number of nodes
3, // replicas
"MasterSlave", IdealState.RebalanceMode.FULL_AUTO, true); // do rebalance
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ClusterConfig clusterConfig = accessor.getProperty(accessor.keyBuilder().clusterConfig());
clusterConfig.setResourcePriorityField("Name");
List<StateTransitionThrottleConfig> throttleConfigs = new ArrayList<>();
throttleConfigs.add(
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 100));
throttleConfigs.add(new StateTransitionThrottleConfig(
StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 100));
clusterConfig.setStateTransitionThrottleConfigs(throttleConfigs);
accessor.setProperty(keyBuilder.clusterConfig(), clusterConfig);
}
private static boolean pollForPartitionAssignment(final HelixDataAccessor accessor,
final MockParticipantManager participant, final String resourceName, final int timeout)
throws Exception {
return TestHelper.verify(() -> {
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
PropertyKey partitionStatusKey = keyBuilder.currentState(participant.getInstanceName(),
participant.getSessionId(), resourceName);
CurrentState currentState = accessor.getProperty(partitionStatusKey);
return currentState != null && !currentState.getPartitionStateMap().isEmpty();
}, timeout);
}
}
| 9,482 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestRebalancerPersistAssignments.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.Collections;
import java.util.Date;
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.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.RebalanceStrategy;
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.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.MasterSlaveSMD;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
private Set<String> _instanceNames = 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);
}
// 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();
}
}
@DataProvider(name = "rebalanceModes")
public static Object[][] rebalanceModes() {
return new RebalanceMode[][] {
{
RebalanceMode.SEMI_AUTO
}, {
RebalanceMode.FULL_AUTO
}
};
}
@Test(dataProvider = "rebalanceModes")
public void testDisablePersist(RebalanceMode rebalanceMode) {
String testDb = "TestDB2-" + rebalanceMode.name();
_gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
BuiltInStateModelDefinitions.LeaderStandby.name(), rebalanceMode.name(),
rebalanceMode.equals(RebalanceMode.FULL_AUTO) ? CrushEdRebalanceStrategy.class.getName()
: RebalanceStrategy.DEFAULT_REBALANCE_STRATEGY);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, 3);
BestPossibleExternalViewVerifier.Builder verifierBuilder =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(new HashSet<>(Collections.singleton(testDb)))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(verifierBuilder.build().verifyByPolling());
// kill 1 node
_participants[0].syncStop();
Set<String> liveInstances = new HashSet<>(_instanceNames);
liveInstances.remove(_participants[0].getInstanceName());
verifierBuilder.setExpectLiveInstances(liveInstances);
Assert.assertTrue(verifierBuilder.build().verifyByPolling());
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
Set<String> excludedInstances = new HashSet<>();
excludedInstances.add(_participants[0].getInstanceName());
verifyAssignmentInIdealStateWithPersistDisabled(idealState, excludedInstances);
// clean up
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
_participants[0] =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[0].getInstanceName());
_participants[0].syncStart();
}
@Test(dataProvider = "rebalanceModes", dependsOnMethods = {
"testDisablePersist"
})
public void testEnablePersist(RebalanceMode rebalanceMode) {
String testDb = "TestDB1-" + rebalanceMode.name();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
BuiltInStateModelDefinitions.LeaderStandby.name(), rebalanceMode.name(),
rebalanceMode.equals(RebalanceMode.FULL_AUTO) ? CrushEdRebalanceStrategy.class.getName()
: RebalanceStrategy.DEFAULT_REBALANCE_STRATEGY);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, 3);
BestPossibleExternalViewVerifier.Builder verifierBuilder =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(new HashSet<>(Collections.singleton(testDb)))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(verifierBuilder.build().verifyByPolling());
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
verifyAssignmentInIdealStateWithPersistEnabled(idealState, new HashSet<>());
// kill 1 node
_participants[0].syncStop();
Set<String> liveInstances = new HashSet<>(_instanceNames);
liveInstances.remove(_participants[0].getInstanceName());
verifierBuilder.setExpectLiveInstances(liveInstances);
Assert.assertTrue(verifierBuilder.build().verifyByPolling());
idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
// verify that IdealState contains updated assignment in it map fields.
Set<String> excludedInstances = new HashSet<>();
excludedInstances.add(_participants[0].getInstanceName());
verifyAssignmentInIdealStateWithPersistEnabled(idealState, excludedInstances);
// clean up
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
_participants[0] =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[0].getInstanceName());
_participants[0].syncStart();
}
/**
* This test is to test the temporary solution for solving Espresso/Databus back-compatible map
* format issue.
*/
@Test(dependsOnMethods = {
"testDisablePersist"
})
public void testSemiAutoEnablePersistMasterSlave() {
String testDb = "TestDB1-MasterSlave";
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.SEMI_AUTO.name());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, 3);
BestPossibleExternalViewVerifier.Builder verifierBuilder =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(new HashSet<>(Collections.singleton(testDb)))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(verifierBuilder.build().verifyByPolling());
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
verifySemiAutoMasterSlaveAssignment(idealState);
// kill 1 node
_participants[0].syncStop();
Set<String> liveInstances = new HashSet<>(_instanceNames);
liveInstances.remove(_participants[0].getInstanceName());
verifierBuilder.setExpectLiveInstances(liveInstances);
Assert.assertTrue(verifierBuilder.build().verifyByPolling());
idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
verifySemiAutoMasterSlaveAssignment(idealState);
// disable an instance
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[1].getInstanceName(), false);
idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
verifySemiAutoMasterSlaveAssignment(idealState);
// clean up
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[1].getInstanceName(), true);
_participants[0].reset();
_participants[0].syncStart();
}
private void verifySemiAutoMasterSlaveAssignment(IdealState idealState) {
for (String partition : idealState.getPartitionSet()) {
Map<String, String> instanceStateMap = idealState.getInstanceStateMap(partition);
List<String> preferenceList = idealState.getPreferenceList(partition);
int numMaster = 0;
for (String ins : preferenceList) {
Assert.assertTrue(instanceStateMap.containsKey(ins),
String.format("Instance %s from preference list not in the map", ins));
String state = instanceStateMap.get(ins);
Assert.assertTrue(state.equals(MasterSlaveSMD.States.MASTER.name())
|| state.equals(MasterSlaveSMD.States.SLAVE.name()), "Actual State" + state);
if (state.equals(MasterSlaveSMD.States.MASTER.name())) {
numMaster++;
}
}
Assert.assertEquals(numMaster, 1);
}
}
// verify that both list field and map field should be persisted in IS,
// And the disabled or failed instance should not be included in bestPossible assignment.
private void verifyAssignmentInIdealStateWithPersistEnabled(IdealState idealState,
Set<String> excludedInstances) {
for (String partition : idealState.getPartitionSet()) {
Map<String, String> instanceStateMap = idealState.getInstanceStateMap(partition);
Assert.assertNotNull(instanceStateMap);
Assert.assertFalse(instanceStateMap.isEmpty());
Set<String> instancesInMap = instanceStateMap.keySet();
if (idealState.getRebalanceMode() == RebalanceMode.SEMI_AUTO) {
Set<String> instanceInList = idealState.getInstanceSet(partition);
Assert.assertTrue(instanceInList.containsAll(instancesInMap));
}
if (idealState.getRebalanceMode() == RebalanceMode.FULL_AUTO) {
// preference list should be persisted in IS.
List<String> instanceList = idealState.getPreferenceList(partition);
Assert.assertNotNull(instanceList);
Assert.assertFalse(instanceList.isEmpty());
for (String ins : excludedInstances) {
Assert.assertFalse(instanceList.contains(ins));
}
}
for (String ins : excludedInstances) {
Assert.assertFalse(instancesInMap.contains(ins));
}
}
}
// verify that the bestPossible assignment should be empty or should not be changed.
private void verifyAssignmentInIdealStateWithPersistDisabled(IdealState idealState,
Set<String> excludedInstances) {
boolean mapFieldEmpty = true;
boolean assignmentNotChanged = false;
for (String partition : idealState.getPartitionSet()) {
Map<String, String> instanceStateMap = idealState.getInstanceStateMap(partition);
if (instanceStateMap == null || instanceStateMap.isEmpty()) {
continue;
}
mapFieldEmpty = false;
Set<String> instancesInMap = instanceStateMap.keySet();
for (String ins : excludedInstances) {
if (instancesInMap.contains(ins)) {
// if at least one excluded instance is included, it means assignment was not updated.
assignmentNotChanged = true;
}
if (idealState.getRebalanceMode() == RebalanceMode.FULL_AUTO) {
List<String> instanceList = idealState.getPreferenceList(partition);
if (instanceList.contains(ins)) {
assignmentNotChanged = true;
}
}
}
}
Assert.assertTrue((mapFieldEmpty || assignmentNotChanged),
"BestPossible assignment was updated.");
}
}
| 9,483 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestComputeAndCleanupCustomizedView.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 java.util.Map;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
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.CustomizedState;
import org.apache.helix.model.CustomizedStateConfig;
import org.apache.helix.model.CustomizedView;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Test compute and clean customized view - if customized state is remove externally, controller
* should remove the
* orphan customized view
*/
public class TestComputeAndCleanupCustomizedView extends ZkUnitTestBase {
private final String RESOURCE_NAME = "TestDB0";
private final String PARTITION_NAME1 = "TestDB0_0";
private final String PARTITION_NAME2 = "TestDB0_1";
private final String CUSTOMIZED_STATE_NAME1 = "customizedState1";
private final String CUSTOMIZED_STATE_NAME2 = "customizedState2";
private final String INSTANCE_NAME1 = "localhost_12918";
private final String INSTANCE_NAME2 = "localhost_12919";
@Test
public void test() 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
2, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
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();
}
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
// add CUSTOMIZED_STATE_NAME2 to aggregation enabled types
CustomizedStateConfig config = new CustomizedStateConfig();
List<String> aggregationEnabledTypes = new ArrayList<>();
aggregationEnabledTypes.add(CUSTOMIZED_STATE_NAME2);
config.setAggregationEnabledTypes(aggregationEnabledTypes);
accessor.setProperty(keyBuilder.customizedStateConfig(), config);
// set INSTANCE1 to "STARTED" for CUSTOMIZED_STATE_NAME1
CustomizedState customizedState = new CustomizedState(RESOURCE_NAME);
customizedState.setState(PARTITION_NAME1, "STARTED");
accessor.setProperty(
keyBuilder.customizedState(INSTANCE_NAME1, CUSTOMIZED_STATE_NAME1, RESOURCE_NAME),
customizedState);
// verify the customized view is empty for CUSTOMIZED_STATE_NAME1
Boolean result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
CustomizedView customizedView =
accessor.getProperty(keyBuilder.customizedView(CUSTOMIZED_STATE_NAME1, RESOURCE_NAME));
if (customizedView == null) {
return true;
}
return false;
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result, String
.format("Customized view should not have state for" + " resource: %s, partition: %s",
RESOURCE_NAME, PARTITION_NAME1));
// add CUSTOMIZED_STATE_NAME1 to aggregation enabled types
aggregationEnabledTypes.add(CUSTOMIZED_STATE_NAME1);
config.setAggregationEnabledTypes(aggregationEnabledTypes);
accessor.setProperty(keyBuilder.customizedStateConfig(), config);
// verify the customized view should have "STARTED" for CUSTOMIZED_STATE_NAME1 for INSTANCE1,
// but no state for INSTANCE2
result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
CustomizedView customizedView =
accessor.getProperty(keyBuilder.customizedView(CUSTOMIZED_STATE_NAME1, RESOURCE_NAME));
if (customizedView != null) {
Map<String, String> stateMap = customizedView.getRecord().getMapField(PARTITION_NAME1);
return (stateMap.get(INSTANCE_NAME1).equals("STARTED"));
}
return false;
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result, String.format(
"Customized view should have the state as STARTED for" + " instance: %s,"
+ " resource: %s, partition: %s and state: %s", INSTANCE_NAME1, RESOURCE_NAME,
PARTITION_NAME1, CUSTOMIZED_STATE_NAME1));
result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
CustomizedView customizedView =
accessor.getProperty(keyBuilder.customizedView(CUSTOMIZED_STATE_NAME1, RESOURCE_NAME));
if (customizedView != null) {
Map<String, String> stateMap = customizedView.getRecord().getMapField(PARTITION_NAME1);
return !stateMap.containsKey(INSTANCE_NAME2);
}
return false;
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result, String
.format("Customized view should not have state for instance: " + "%s", INSTANCE_NAME2));
// set INSTANCE2 to "STARTED" for CUSTOMIZED_STATE_NAME1
customizedState = new CustomizedState(RESOURCE_NAME);
customizedState.setState(PARTITION_NAME1, "STARTED");
accessor.setProperty(
keyBuilder.customizedState(INSTANCE_NAME2, CUSTOMIZED_STATE_NAME1, RESOURCE_NAME),
customizedState);
result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
CustomizedView customizedView =
accessor.getProperty(keyBuilder.customizedView(CUSTOMIZED_STATE_NAME1, RESOURCE_NAME));
if (customizedView != null) {
Map<String, String> stateMap = customizedView.getRecord().getMapField(PARTITION_NAME1);
if (stateMap.containsKey(INSTANCE_NAME2)) {
return (stateMap.get(INSTANCE_NAME1).equals("STARTED") && stateMap.get(INSTANCE_NAME2)
.equals("STARTED"));
}
}
return false;
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result, String.format(
"Customized view should have both instances state " + "as STARTED for"
+ " resource: %s, partition: %s and state: %s", RESOURCE_NAME, PARTITION_NAME1,
CUSTOMIZED_STATE_NAME1));
// set INSTANCE2 to "STARTED" for CUSTOMIZED_STATE_NAME2
customizedState = new CustomizedState(RESOURCE_NAME);
customizedState.setState(PARTITION_NAME2, "STARTED");
accessor.setProperty(
keyBuilder.customizedState(INSTANCE_NAME2, CUSTOMIZED_STATE_NAME2, RESOURCE_NAME),
customizedState);
result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
CustomizedView customizedView =
accessor.getProperty(keyBuilder.customizedView(CUSTOMIZED_STATE_NAME2, RESOURCE_NAME));
if (customizedView != null) {
Map<String, String> stateMap = customizedView.getRecord().getMapField(PARTITION_NAME2);
return (stateMap.get(INSTANCE_NAME2).equals("STARTED"));
}
return false;
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result, String.format(
"Customized view should have state " + "as STARTED " + "for instance: %s, "
+ " resource: %s, partition: %s and state: %s", INSTANCE_NAME2, RESOURCE_NAME,
PARTITION_NAME2, CUSTOMIZED_STATE_NAME2));
// remove CUSTOMIZED_STATE_NAME1 from aggregation enabled types
aggregationEnabledTypes.remove(CUSTOMIZED_STATE_NAME1);
config.setAggregationEnabledTypes(aggregationEnabledTypes);
accessor.setProperty(keyBuilder.customizedStateConfig(), config);
result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
CustomizedView customizedView =
accessor.getProperty(keyBuilder.customizedView(CUSTOMIZED_STATE_NAME1, RESOURCE_NAME));
if (customizedView == null) {
return true;
}
return false;
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result,
String.format("Customized view should not have state %s", CUSTOMIZED_STATE_NAME1));
// disable controller
ZKHelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.enableCluster(clusterName, false);
ZkTestHelper.tryWaitZkEventsCleaned(controller.getZkClient());
// drop resource
admin.dropResource(clusterName, RESOURCE_NAME);
// delete customized state manually, controller shall remove customized view when cluster is
//enabled again
accessor.removeProperty(
keyBuilder.customizedState(INSTANCE_NAME1, CUSTOMIZED_STATE_NAME1, RESOURCE_NAME));
accessor.removeProperty(
keyBuilder.currentState(INSTANCE_NAME2, CUSTOMIZED_STATE_NAME1, RESOURCE_NAME));
// re-enable controller shall remove orphan external view
// System.out.println("re-enabling controller");
admin.enableCluster(clusterName, true);
result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
CustomizedView customizedView =
accessor.getProperty(keyBuilder.customizedView(CUSTOMIZED_STATE_NAME1));
if (customizedView == null) {
return true;
}
return false;
}
}, 12000);
Thread.sleep(50);
Assert.assertTrue(result, String
.format("customized view for should be null for resource: %s, partition: %s and state: %s",
RESOURCE_NAME, PARTITION_NAME1, CUSTOMIZED_STATE_NAME1));
// 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,484 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestCustomizedViewAggregation.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.Collection;
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.TreeMap;
import com.google.common.collect.Maps;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyType;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.customizedstate.CustomizedStateProvider;
import org.apache.helix.customizedstate.CustomizedStateProviderFactory;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.CustomizedState;
import org.apache.helix.model.CustomizedStateConfig;
import org.apache.helix.model.CustomizedView;
import org.apache.helix.spectator.RoutingTableProvider;
import org.apache.helix.spectator.RoutingTableSnapshot;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestCustomizedViewAggregation extends ZkUnitTestBase {
private static CustomizedStateProvider _customizedStateProvider_participant0;
private static CustomizedStateProvider _customizedStateProvider_participant1;
private static RoutingTableProvider _routingTableProvider;
private static HelixManager _spectator;
private static HelixManager _manager;
// 1st key: customized state type, 2nd key: resource name, 3rd key: partition name, 4th key: instance name, value: state value
// This map contains all the customized state information that is updated to ZooKeeper
private static Map<String, Map<String, Map<String, Map<String, String>>>> _localCustomizedView;
// The set contains customized state types that are enabled for aggregation in config
private static Set<String> _aggregationEnabledTypes;
// The set contains customized state types that routing table provider shows to users
private static Set<String> _routingTableProviderDataSources;
private String INSTANCE_0;
private String INSTANCE_1;
private final String RESOURCE_0 = "TestDB0";
private final String RESOURCE_1 = "TestDB1";
private final String PARTITION_00 = "TestDB0_0";
private final String PARTITION_01 = "TestDB0_1";
private final String PARTITION_10 = "TestDB1_0";
private final String PARTITION_11 = "TestDB1_1";
private MockParticipantManager[] _participants;
private ClusterControllerManager _controller;
// Customized state values used for test, TYPE_A_0 - TYPE_A_2 are values for Customized state TypeA, etc.
private enum CurrentStateValues {
TYPE_A_0, TYPE_A_1, TYPE_A_2, TYPE_B_0, TYPE_B_1, TYPE_B_2, TYPE_C_0, TYPE_C_1, TYPE_C_2
}
private enum CustomizedStateType {
TYPE_A, TYPE_B, TYPE_C
}
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
String clusterName = TestHelper.getTestClassName();
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
2, // resources
2, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
_controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
_controller.syncStart();
// start participants
_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();
}
INSTANCE_0 = _participants[0].getInstanceName();
INSTANCE_1 = _participants[1].getInstanceName();
_manager = HelixManagerFactory
.getZKHelixManager(clusterName, "admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
_manager.connect();
_spectator = HelixManagerFactory
.getZKHelixManager(clusterName, "spectator", InstanceType.SPECTATOR, ZK_ADDR);
_spectator.connect();
// Initialize customized state provider
_customizedStateProvider_participant0 = CustomizedStateProviderFactory.getInstance()
.buildCustomizedStateProvider(_manager, _participants[0].getInstanceName());
_customizedStateProvider_participant1 = CustomizedStateProviderFactory.getInstance()
.buildCustomizedStateProvider(_manager, _participants[1].getInstanceName());
_localCustomizedView = new HashMap<>();
_routingTableProviderDataSources = new HashSet<>();
_aggregationEnabledTypes = new HashSet<>();
List<String> customizedStateTypes = Arrays
.asList(CustomizedStateType.TYPE_A.name(), CustomizedStateType.TYPE_B.name(),
CustomizedStateType.TYPE_C.name());
CustomizedStateConfig.Builder customizedStateConfigBuilder =
new CustomizedStateConfig.Builder();
customizedStateConfigBuilder.setAggregationEnabledTypes(customizedStateTypes);
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
accessor.setProperty(accessor.keyBuilder().customizedStateConfig(),
customizedStateConfigBuilder.build());
_aggregationEnabledTypes.addAll(customizedStateTypes);
Map<PropertyType, List<String>> dataSource = new HashMap<>();
dataSource.put(PropertyType.CUSTOMIZEDVIEW, customizedStateTypes);
_routingTableProvider = new RoutingTableProvider(_spectator, dataSource);
_routingTableProviderDataSources.addAll(customizedStateTypes);
}
@AfterClass
public void afterClass() {
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
_routingTableProvider.shutdown();
_manager.disconnect();
_spectator.disconnect();
}
/**
* Compare the customized view values between ZK and local record
* @throws Exception thread interrupted exception
*/
private void validateAggregationSnapshot() throws Exception {
boolean result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
Map<String, Map<String, RoutingTableSnapshot>> routingTableSnapshots =
_routingTableProvider.getRoutingTableSnapshots();
// Get customized view snapshot
Map<String, RoutingTableSnapshot> fullCustomizedViewSnapshot =
routingTableSnapshots.get(PropertyType.CUSTOMIZEDVIEW.name());
if (fullCustomizedViewSnapshot.isEmpty() && !_routingTableProviderDataSources.isEmpty()) {
return false;
}
for (String customizedStateType : fullCustomizedViewSnapshot.keySet()) {
if (!_routingTableProviderDataSources.contains(customizedStateType)) {
return false;
}
// Get per customized state type snapshot
RoutingTableSnapshot customizedViewSnapshot =
fullCustomizedViewSnapshot.get(customizedStateType);
// local per customized state type map
Map<String, Map<String, Map<String, String>>> localSnapshot =
_localCustomizedView.getOrDefault(customizedStateType, Maps.newHashMap());
Collection<CustomizedView> customizedViews = customizedViewSnapshot.getCustomizeViews();
// If a customized state is not set to be aggregated in config, but is enabled in routing table provider, it will show up in customized view returned to user, but will be empty
if (!_aggregationEnabledTypes.contains(customizedStateType)
&& customizedViews.size() != 0) {
return false;
}
if (_aggregationEnabledTypes.contains(customizedStateType)
&& customizedViews.size() != localSnapshot.size()) {
return false;
}
// Get per resource snapshot
for (CustomizedView resourceCustomizedView : customizedViews) {
ZNRecord record = resourceCustomizedView.getRecord();
Map<String, Map<String, String>> resourceStateMap = record.getMapFields();
// Get local per resource map
Map<String, Map<String, String>> localPerResourceCustomizedView = localSnapshot
.getOrDefault(resourceCustomizedView.getResourceName(), Maps.newHashMap());
if (resourceStateMap.size() != localPerResourceCustomizedView.size()) {
return false;
}
// Get per partition snapshot
for (String partitionName : resourceStateMap.keySet()) {
Map<String, String> stateMap =
resourceStateMap.getOrDefault(partitionName, Maps.newTreeMap());
// Get local per partition map
Map<String, String> localStateMap =
localPerResourceCustomizedView.getOrDefault(partitionName, Maps.newTreeMap());
if (stateMap.isEmpty() && !localStateMap.isEmpty()) {
return false;
}
for (String instanceName : stateMap.keySet()) {
// Per instance value
String stateMapValue = stateMap.get(instanceName);
String localStateMapValue = localStateMap.get(instanceName);
if (!stateMapValue.equals(localStateMapValue)) {
return false;
}
}
}
}
}
return true;
}
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
}
/**
* Update the local record of customized view
* @param instanceName the instance to be updated
* @param customizedStateType the customized state type to be updated
* @param resourceName the resource to be updated
* @param partitionName the partition to be updated
* @param customizedStateValue if update, this will be the value to update; a null value indicate delete operation
*/
private void updateLocalCustomizedViewMap(String instanceName,
CustomizedStateType customizedStateType, String resourceName, String partitionName,
CurrentStateValues customizedStateValue) {
_localCustomizedView.putIfAbsent(customizedStateType.name(), new TreeMap<>());
Map<String, Map<String, Map<String, String>>> localPerStateType =
_localCustomizedView.get(customizedStateType.name());
localPerStateType.putIfAbsent(resourceName, new TreeMap<>());
Map<String, Map<String, String>> localPerResource = localPerStateType.get(resourceName);
localPerResource.putIfAbsent(partitionName, new TreeMap<>());
Map<String, String> localPerPartition = localPerResource.get(partitionName);
if (customizedStateValue == null) {
localPerPartition.remove(instanceName);
if (localPerPartition.isEmpty()) {
localPerResource.remove(partitionName);
}
} else {
localPerPartition.put(instanceName, customizedStateValue.name());
}
}
/**
* Call this method in the test for an update on customized view in both ZK and local map
* @param instanceName the instance to be updated
* @param customizedStateType the customized state type to be updated
* @param resourceName the resource to be updated
* @param partitionName the partition to be updated
* @param customizedStateValue if update, this will be the value to update; a null value indicate delete operation
* @throws Exception if the input instance name is not valid
*/
private void update(String instanceName, CustomizedStateType customizedStateType,
String resourceName, String partitionName, CurrentStateValues customizedStateValue)
throws Exception {
if (instanceName.equals(INSTANCE_0)) {
_customizedStateProvider_participant0
.updateCustomizedState(customizedStateType.name(), resourceName, partitionName,
customizedStateValue.name());
updateLocalCustomizedViewMap(INSTANCE_0, customizedStateType, resourceName, partitionName,
customizedStateValue);
} else if (instanceName.equals(INSTANCE_1)) {
_customizedStateProvider_participant1
.updateCustomizedState(customizedStateType.name(), resourceName, partitionName,
customizedStateValue.name());
updateLocalCustomizedViewMap(INSTANCE_1, customizedStateType, resourceName, partitionName,
customizedStateValue);
} else {
throw new Exception("The input instance name is not valid.");
}
}
/**
*
* Call this method in the test for an delete on customized view in both ZK and local map
* @param instanceName the instance to be updated
* @param customizedStateType the customized state type to be updated
* @param resourceName the resource to be updated
* @param partitionName the partition to be updated
* @throws Exception if the input instance name is not valid
*/
private void delete(String instanceName, CustomizedStateType customizedStateType,
String resourceName, String partitionName) throws Exception {
if (instanceName.equals(INSTANCE_0)) {
_customizedStateProvider_participant0
.deletePerPartitionCustomizedState(customizedStateType.name(), resourceName,
partitionName);
updateLocalCustomizedViewMap(INSTANCE_0, customizedStateType, resourceName, partitionName,
null);
} else if (instanceName.equals(INSTANCE_1)) {
_customizedStateProvider_participant1
.deletePerPartitionCustomizedState(customizedStateType.name(), resourceName,
partitionName);
updateLocalCustomizedViewMap(INSTANCE_1, customizedStateType, resourceName, partitionName,
null);
} else {
throw new Exception("The input instance name is not valid.");
}
}
/**
* Set the data sources (customized state types) for routing table provider
* @param customizedStateTypes list of customized state types that routing table provider will include in the snapshot shown to users
*/
/**
* Set the customized view aggregation config in controller
* @param aggregationEnabledTypes list of customized state types that the controller will aggregate to customized view
*/
private void setAggregationEnabledTypes(List<CustomizedStateType> aggregationEnabledTypes) {
List<String> enabledTypes = new ArrayList<>();
_aggregationEnabledTypes.clear();
for (CustomizedStateType type : aggregationEnabledTypes) {
enabledTypes.add(type.name());
_aggregationEnabledTypes.add(type.name());
}
CustomizedStateConfig.Builder customizedStateConfigBuilder =
new CustomizedStateConfig.Builder();
customizedStateConfigBuilder.setAggregationEnabledTypes(enabledTypes);
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
accessor.setProperty(accessor.keyBuilder().customizedStateConfig(),
customizedStateConfigBuilder.build());
}
@Test
public void testCustomizedViewAggregation() throws Exception {
// Aggregating: Type A, Type B, Type C
// Routing table: Type A, Type B, Type C
update(INSTANCE_0, CustomizedStateType.TYPE_A, RESOURCE_0, PARTITION_00,
CurrentStateValues.TYPE_A_0);
update(INSTANCE_0, CustomizedStateType.TYPE_B, RESOURCE_0, PARTITION_00,
CurrentStateValues.TYPE_B_0);
update(INSTANCE_0, CustomizedStateType.TYPE_B, RESOURCE_0, PARTITION_01,
CurrentStateValues.TYPE_B_1);
update(INSTANCE_0, CustomizedStateType.TYPE_A, RESOURCE_1, PARTITION_11,
CurrentStateValues.TYPE_A_1);
update(INSTANCE_1, CustomizedStateType.TYPE_C, RESOURCE_0, PARTITION_00,
CurrentStateValues.TYPE_C_0);
update(INSTANCE_1, CustomizedStateType.TYPE_C, RESOURCE_0, PARTITION_01,
CurrentStateValues.TYPE_C_1);
update(INSTANCE_1, CustomizedStateType.TYPE_B, RESOURCE_1, PARTITION_10,
CurrentStateValues.TYPE_B_2);
update(INSTANCE_1, CustomizedStateType.TYPE_C, RESOURCE_1, PARTITION_10,
CurrentStateValues.TYPE_C_2);
update(INSTANCE_1, CustomizedStateType.TYPE_A, RESOURCE_1, PARTITION_11,
CurrentStateValues.TYPE_A_1);
validateAggregationSnapshot();
Assert.assertNull(_customizedStateProvider_participant0
.getCustomizedState(CustomizedStateType.TYPE_C.name(), RESOURCE_0));
// Test batch update API to update several customized state fields in the same customized state, but for now only CURRENT_STATE will be aggregated in customized view
Map<String, String> customizedStates = Maps.newHashMap();
customizedStates.put("CURRENT_STATE", CurrentStateValues.TYPE_A_2.name());
customizedStates.put("PREVIOUS_STATE", CurrentStateValues.TYPE_A_0.name());
_customizedStateProvider_participant1
.updateCustomizedState(CustomizedStateType.TYPE_A.name(), RESOURCE_1, PARTITION_10,
customizedStates);
updateLocalCustomizedViewMap(INSTANCE_1, CustomizedStateType.TYPE_A, RESOURCE_1, PARTITION_10,
CurrentStateValues.TYPE_A_2);
validateAggregationSnapshot();
// Aggregating: Type A
// Routing table: Type A, Type B, Type C
setAggregationEnabledTypes(Arrays.asList(CustomizedStateType.TYPE_A));
// This is commented out as a work around to pass the test
// The validation of config change will be done combined with the next several customized state changes
// The next validation should only show TYPE_A states aggregated in customized view
// Until we fix the issue in routing table provider https://github.com/apache/helix/issues/1296
// validateAggregationSnapshot();
// Test get customized state and get per partition customized state via customized state provider, this part of test doesn't change customized view
CustomizedState customizedState = _customizedStateProvider_participant1
.getCustomizedState(CustomizedStateType.TYPE_A.name(), RESOURCE_1);
Assert.assertEquals(customizedState.getState(PARTITION_10), CurrentStateValues.TYPE_A_2.name());
Assert.assertEquals(customizedState.getPreviousState(PARTITION_10),
CurrentStateValues.TYPE_A_0.name());
Assert.assertEquals(customizedState.getState(PARTITION_11), CurrentStateValues.TYPE_A_1.name());
Map<String, String> perPartitionCustomizedState = _customizedStateProvider_participant1
.getPerPartitionCustomizedState(CustomizedStateType.TYPE_A.name(), RESOURCE_1,
PARTITION_10);
// Remove this field because it's automatically updated for monitoring purpose and we don't need to compare it
perPartitionCustomizedState.remove(CustomizedState.CustomizedStateProperty.START_TIME.name());
Map<String, String> actualPerPartitionCustomizedState = Maps.newHashMap();
actualPerPartitionCustomizedState
.put(CustomizedState.CustomizedStateProperty.CURRENT_STATE.name(),
CurrentStateValues.TYPE_A_2.name());
actualPerPartitionCustomizedState
.put(CustomizedState.CustomizedStateProperty.PREVIOUS_STATE.name(),
CurrentStateValues.TYPE_A_0.name());
Assert.assertEquals(perPartitionCustomizedState, actualPerPartitionCustomizedState);
// Test delete per partition customized state via customized state provider.
_customizedStateProvider_participant1
.deletePerPartitionCustomizedState(CustomizedStateType.TYPE_A.name(), RESOURCE_1,
PARTITION_10);
customizedState = _customizedStateProvider_participant1
.getCustomizedState(CustomizedStateType.TYPE_A.name(), RESOURCE_1);
Assert.assertEquals(customizedState.getState(PARTITION_11), CurrentStateValues.TYPE_A_1.name());
Assert.assertNull(_customizedStateProvider_participant1
.getPerPartitionCustomizedState(CustomizedStateType.TYPE_A.name(), RESOURCE_1,
PARTITION_10));
// Customized view only reflect CURRENT_STATE field
updateLocalCustomizedViewMap(INSTANCE_1, CustomizedStateType.TYPE_A, RESOURCE_1, PARTITION_10,
null);
validateAggregationSnapshot();
// Update some customized states and verify
delete(INSTANCE_0, CustomizedStateType.TYPE_A, RESOURCE_0, PARTITION_00);
delete(INSTANCE_1, CustomizedStateType.TYPE_B, RESOURCE_1, PARTITION_10);
// delete a customize state that does not exist
delete(INSTANCE_1, CustomizedStateType.TYPE_A, RESOURCE_1, PARTITION_10);
validateAggregationSnapshot();
// Aggregating: Type A, Type B, Type C
// Routing table: Type A, Type B, Type C
setAggregationEnabledTypes(Arrays.asList(CustomizedStateType.TYPE_A, CustomizedStateType.TYPE_B,
CustomizedStateType.TYPE_C));
validateAggregationSnapshot();
update(INSTANCE_0, CustomizedStateType.TYPE_B, RESOURCE_0, PARTITION_01,
CurrentStateValues.TYPE_B_2);
update(INSTANCE_1, CustomizedStateType.TYPE_B, RESOURCE_1, PARTITION_10,
CurrentStateValues.TYPE_B_1);
update(INSTANCE_1, CustomizedStateType.TYPE_C, RESOURCE_1, PARTITION_10,
CurrentStateValues.TYPE_C_0);
update(INSTANCE_0, CustomizedStateType.TYPE_A, RESOURCE_1, PARTITION_11,
CurrentStateValues.TYPE_A_0);
validateAggregationSnapshot();
}
}
| 9,485 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDisableExternalView.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.HelixProperty;
import org.apache.helix.PropertyKey;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
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.tools.ClusterStateVerifier;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Test disable external-view in resource ideal state -
* if DISABLE_EXTERNAL_VIEW is set to true in a resource's idealstate,
* there should be no external view for this resource.
*/
public class TestDisableExternalView extends ZkTestBase {
private static final String TEST_DB1 = "test_db1";
private static final String TEST_DB2 = "test_db2";
private static final int NODE_NR = 5;
private static final int START_PORT = 12918;
private static final String STATE_MODEL = "MasterSlave";
private static final int _PARTITIONS = 20;
private final String CLASS_NAME = getShortClassName();
private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
private MockParticipantManager[] _participants = new MockParticipantManager[NODE_NR];
private ClusterControllerManager _controller;
private String [] instances = new String[NODE_NR];
private ZKHelixAdmin _admin;
int _replica = 3;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_admin = new ZKHelixAdmin(_gZkClient);
String namespace = "/" + CLUSTER_NAME;
if (_gZkClient.exists(namespace)) {
_gZkClient.deleteRecursively(namespace);
}
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB1, _PARTITIONS, STATE_MODEL,
IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
IdealState idealState = _admin.getResourceIdealState(CLUSTER_NAME, TEST_DB1);
idealState.setDisableExternalView(true);
_admin.setResourceIdealState(CLUSTER_NAME, TEST_DB1, idealState);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB2, _PARTITIONS, STATE_MODEL,
IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
for (int i = 0; i < NODE_NR; i++) {
instances[i] = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instances[i]);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB1, _replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB2, _replica);
// 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();
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
}
@Test
public void testDisableExternalView() throws InterruptedException {
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
// verify external view for TEST_DB1 does not exist
ExternalView externalView = null;
externalView = accessor.getProperty(keyBuilder.externalView(TEST_DB1));
Assert.assertNull(externalView,
"There should be no external-view for " + TEST_DB1 + ", but is: " + externalView);
// verify external view for TEST_DB2 exists
externalView = accessor.getProperty(keyBuilder.externalView(TEST_DB2));
Assert.assertNotNull(externalView,
"Could not find external-view for " + TEST_DB2);
// disable external view in IS
IdealState idealState = _admin.getResourceIdealState(CLUSTER_NAME, TEST_DB2);
idealState.setDisableExternalView(true);
_admin.setResourceIdealState(CLUSTER_NAME, TEST_DB2, idealState);
// touch liveinstance to trigger externalview compute stage
String instance = PARTICIPANT_PREFIX + "_" + START_PORT;
HelixProperty liveInstance = accessor.getProperty(keyBuilder.liveInstance(instance));
accessor.setProperty(keyBuilder.liveInstance(instance), liveInstance);
// verify the external view for the db got removed
for (int i = 0; i < 10; i++) {
Thread.sleep(100);
externalView = accessor.getProperty(keyBuilder.externalView(TEST_DB2));
if (externalView == null) {
break;
}
}
Assert.assertNull(externalView, "external-view for " + TEST_DB2 + " should be removed, but was: "
+ externalView);
}
@AfterClass
public void afterClass() {
// clean up
_controller.syncStop();
for (int i = 0; i < NODE_NR; i++) {
_participants[i].syncStop();
}
deleteCluster(CLUSTER_NAME);
}
}
| 9,486 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDisablePartition.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.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.rebalancer.AutoRebalancer;
import org.apache.helix.controller.rebalancer.DelayedAutoRebalancer;
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.ZKHelixAdmin;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestDisablePartition extends ZkStandAloneCMTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestDisablePartition.class);
@Test()
public void testDisablePartition() throws Exception {
LOG.info("START testDisablePartition() at " + new Date(System.currentTimeMillis()));
// localhost_12919 is MASTER for TestDB_0
String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + CLUSTER_NAME
+ " localhost_12919 TestDB TestDB_0 TestDB_9";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Map<String, Set<String>> map = new HashMap<>();
map.put("TestDB_0", TestHelper.setOf("localhost_12919"));
map.put("TestDB_9", TestHelper.setOf("localhost_12919"));
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
TestHelper.verifyState(CLUSTER_NAME, ZK_ADDR, map, "OFFLINE");
ZKHelixAdmin tool = new ZKHelixAdmin(_gZkClient);
tool.enablePartition(true, CLUSTER_NAME, "localhost_12919", "TestDB",
Collections.singletonList("TestDB_9"));
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
map.clear();
map.put("TestDB_0", TestHelper.setOf("localhost_12919"));
TestHelper.verifyState(CLUSTER_NAME, ZK_ADDR, map, "OFFLINE");
map.clear();
map.put("TestDB_9", TestHelper.setOf("localhost_12919"));
TestHelper.verifyState(CLUSTER_NAME, ZK_ADDR, map, "MASTER");
LOG.info("STOP testDisablePartition() at " + new Date(System.currentTimeMillis()));
}
@DataProvider(name = "rebalancer")
public static String[][] rebalancers() {
return new String[][] {
{
AutoRebalancer.class.getName()
}, {
DelayedAutoRebalancer.class.getName()
}
};
}
@Test(dataProvider = "rebalancer", enabled = true)
public void testDisableFullAuto(String rebalancerName) throws Exception {
final int NUM_PARTITIONS = 8;
final int NUM_PARTICIPANTS = 2;
final int NUM_REPLICAS = 1;
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
ClusterSetup clusterSetup = new ClusterSetup(ZK_ADDR);
clusterSetup.addCluster(clusterName, true);
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
String instanceName = "localhost_" + (11420 + i);
clusterSetup.addInstanceToCluster(clusterName, instanceName);
}
// Create a known problematic scenario
HelixAdmin admin = clusterSetup.getClusterManagementTool();
String resourceName = "MailboxDB";
IdealState idealState = new IdealState(resourceName + "DR");
idealState.setRebalanceMode(RebalanceMode.SEMI_AUTO);
idealState.setStateModelDefRef("LeaderStandby");
idealState.setReplicas(String.valueOf(NUM_REPLICAS));
idealState.setNumPartitions(NUM_PARTITIONS);
for (int i = 0; i < NUM_PARTITIONS; i++) {
String partitionName = resourceName + '_' + i;
List<String> assignmentList = Lists.newArrayList();
if (i < NUM_PARTITIONS / 2) {
assignmentList.add("localhost_11420");
} else {
assignmentList.add("localhost_11421");
}
Map<String, String> emptyMap = Maps.newHashMap();
idealState.getRecord().setListField(partitionName, assignmentList);
idealState.getRecord().setMapField(partitionName, emptyMap);
}
admin.addResource(clusterName, idealState.getResourceName(), idealState);
// Start everything
MockParticipantManager[] participants = new MockParticipantManager[NUM_PARTICIPANTS];
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
String instanceName = "localhost_" + (11420 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_1");
controller.syncStart();
Thread.sleep(1000);
// Switch to full auto
idealState.setRebalanceMode(RebalanceMode.FULL_AUTO);
idealState.setRebalancerClassName(rebalancerName);
for (int i = 0; i < NUM_PARTITIONS; i++) {
List<String> emptyList = Collections.emptyList();
idealState.getRecord().setListField(resourceName + '_' + i, emptyList);
}
admin.setResourceIdealState(clusterName, idealState.getResourceName(), idealState);
Thread.sleep(1000);
// Get the external view
HelixDataAccessor accessor = controller.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ExternalView externalView =
accessor.getProperty(keyBuilder.externalView(idealState.getResourceName()));
// Disable the partitions in an order known to cause problems
int[] pid = {
0, 7
};
for (int value : pid) {
String partitionName = resourceName + '_' + value;
Map<String, String> stateMap = externalView.getStateMap(partitionName);
String leader = null;
for (String participantName : stateMap.keySet()) {
String state = stateMap.get(participantName);
if (state.equals("LEADER")) {
leader = participantName;
}
}
List<String> partitionNames = Lists.newArrayList(partitionName);
admin.enablePartition(false, clusterName, leader, idealState.getResourceName(), partitionNames);
Thread.sleep(1000);
}
// Ensure that nothing was reassigned and the disabled are offline
externalView = accessor.getProperty(keyBuilder.externalView(idealState.getResourceName()));
Map<String, String> p0StateMap = externalView.getStateMap(resourceName + "_0");
Assert.assertEquals(p0StateMap.size(), 1);
String p0Participant = p0StateMap.keySet().iterator().next();
Assert.assertEquals(p0StateMap.get(p0Participant), "OFFLINE");
Map<String, String> p7StateMap = externalView.getStateMap(resourceName + "_7");
Assert.assertEquals(p7StateMap.size(), 1);
String p7Participant = p7StateMap.keySet().iterator().next();
Assert.assertEquals(p7StateMap.get(p7Participant), "OFFLINE");
// Cleanup
controller.syncStop();
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
deleteCluster(clusterName);
}
}
| 9,487 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestResourceWithSamePartitionKey.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 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.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.testng.Assert;
import org.testng.annotations.Test;
/**
* @see HELIX-552
* StateModelFactory#_stateModelMap should use both resourceName and partitionKey to map a
* state model
*/
public class TestResourceWithSamePartitionKey extends ZkUnitTestBase {
@Test
public void test() 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
2, // partitions per resource
n, // number of nodes
2, // replicas
"OnlineOffline", RebalanceMode.CUSTOMIZED, false); // do rebalance
HelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
idealState.setReplicas("2");
idealState.setPartitionState("0", "localhost_12918", "ONLINE");
idealState.setPartitionState("0", "localhost_12919", "ONLINE");
idealState.setPartitionState("1", "localhost_12918", "ONLINE");
idealState.setPartitionState("1", "localhost_12919", "ONLINE");
accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
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();
}
boolean result =
ClusterStateVerifier
.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// add a second resource with the same partition-key
IdealState newIdealState = new IdealState("TestDB1");
newIdealState.getRecord().setSimpleFields(idealState.getRecord().getSimpleFields());
newIdealState.setPartitionState("0", "localhost_12918", "ONLINE");
newIdealState.setPartitionState("0", "localhost_12919", "ONLINE");
newIdealState.setPartitionState("1", "localhost_12918", "ONLINE");
newIdealState.setPartitionState("1", "localhost_12919", "ONLINE");
accessor.setProperty(keyBuilder.idealStates("TestDB1"), newIdealState);
result =
ClusterStateVerifier
.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// assert no ERROR
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
List<String> errs = accessor.getChildNames(keyBuilder.errors(instanceName));
Assert.assertTrue(errs.isEmpty());
}
// 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,488 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestZkConnectionLost.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.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.SystemPropertyKeys;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.integration.task.MockTask;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.integration.task.TaskTestUtil;
import org.apache.helix.integration.task.WorkflowGenerator;
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.task.JobConfig;
import org.apache.helix.task.JobQueue;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.WorkflowContext;
import org.apache.helix.tools.ClusterSetup;
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.impl.factory.SharedZkClientFactory;
import org.apache.helix.zookeeper.zkclient.ZkServer;
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 TestZkConnectionLost extends TaskTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TestZkConnectionLost.class);
private final AtomicReference<ZkServer> _zkServerRef = new AtomicReference<>();
private String _zkAddr = "localhost:21893";
private ClusterSetup _setupTool;
private HelixZkClient _zkClient;
@BeforeClass
public void beforeClass() throws Exception {
ZkServer zkServer = TestHelper.startZkServer(_zkAddr);
_zkServerRef.set(zkServer);
_zkClient = SharedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(_zkAddr));
_zkClient.setZkSerializer(new ZNRecordSerializer());
_setupTool = new ClusterSetup(_zkClient);
_participants = new MockParticipantManager[_numNodes];
_setupTool.addCluster(CLUSTER_NAME, true);
setupParticipants(_setupTool);
setupDBs(_setupTool);
createManagers(_zkAddr, CLUSTER_NAME);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(_zkAddr, CLUSTER_NAME, controllerName);
_controller.syncStart();
ZkHelixClusterVerifier clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(_zkAddr)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(clusterVerifier.verifyByPolling());
} finally {
clusterVerifier.close();
}
}
@AfterClass
public void afterClass() throws Exception {
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
if (_manager != null && _manager.isConnected()) {
_manager.disconnect();
}
stopParticipants();
TestHelper.dropCluster(CLUSTER_NAME, _zkClient, _setupTool);
_zkClient.close();
TestHelper.stopZkServer(_zkServerRef.get());
}
@Test
public void testDisconnectWhenConnectionBreak() throws Exception {
String controllerName = CONTROLLER_PREFIX + "_" + TestHelper.getTestMethodName();
ClusterControllerManager controllerManager =
new ClusterControllerManager(_zkAddr, CLUSTER_NAME, controllerName);
controllerManager.syncStart();
TestHelper.stopZkServer(_zkServerRef.get());
AtomicBoolean disconnected = new AtomicBoolean(false);
Thread testThread = new Thread("Testing HelixManager disconnect") {
@Override
public void run() {
try {
controllerManager.disconnect();
} finally {
disconnected.set(true);
}
}
};
try {
testThread.start();
testThread.join();
Assert.assertTrue(disconnected.get());
Assert.assertFalse(controllerManager.isConnected());
} finally {
testThread.interrupt();
_zkServerRef.set(TestHelper.startZkServer(_zkAddr, null, false));
}
}
@Test
public void testLostZkConnection() throws Exception {
System.setProperty(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT, "5000");
System.setProperty(SystemPropertyKeys.ZK_SESSION_TIMEOUT, "5000");
try {
String queueName = TestHelper.getTestMethodName();
startParticipants(_zkAddr);
HelixDataAccessor accessor =
new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor(_zkAddr));
Assert.assertTrue(TestHelper.verify(() -> {
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (MockParticipantManager participant : _participants) {
if (!liveInstances.contains(participant.getInstanceName())
|| !participant.isConnected()) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION));
// Create a queue
LOG.info("Starting job-queue: " + queueName);
JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName, 0, 60);
createAndEnqueueJob(queueBuild, 3);
_driver.start(queueBuild.build());
restartZkServer();
try {
WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName);
String scheduledQueue = wCtx.getLastScheduledSingleWorkflow();
_driver.pollForWorkflowState(scheduledQueue, 30000, TaskState.COMPLETED);
} catch (Exception e) {
// 2nd try because ZK connection problem might prevent the first recurrent workflow to get
// scheduled
WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName);
String scheduledQueue = wCtx.getLastScheduledSingleWorkflow();
_driver.pollForWorkflowState(scheduledQueue, 30000, TaskState.COMPLETED);
}
} finally {
System.clearProperty(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT);
System.clearProperty(SystemPropertyKeys.ZK_SESSION_TIMEOUT);
}
}
@Test(dependsOnMethods = {
"testLostZkConnection"
}, enabled = false)
public void testLostZkConnectionNegative() throws Exception {
System.setProperty(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT, "10");
System.setProperty(SystemPropertyKeys.ZK_SESSION_TIMEOUT, "1000");
try {
String queueName = TestHelper.getTestMethodName();
stopParticipants();
startParticipants(_zkAddr);
LOG.info("Starting job-queue: " + queueName);
JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName, 0, 6000);
createAndEnqueueJob(queueBuild, 3);
_driver.start(queueBuild.build());
restartZkServer();
WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName);
// ensure job 1 is started before stop it
String scheduledQueue = wCtx.getLastScheduledSingleWorkflow();
try {
_driver.pollForWorkflowState(scheduledQueue, 30000, TaskState.COMPLETED);
Assert.fail("Test failure!");
} catch (HelixException ex) {
// test succeeded
}
} finally {
System.clearProperty(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT);
System.clearProperty(SystemPropertyKeys.ZK_SESSION_TIMEOUT);
}
}
private void restartZkServer() throws ExecutionException, InterruptedException {
// shutdown and restart zk for a couple of times
for (int i = 0; i < 4; i++) {
Executors.newSingleThreadExecutor().submit(() -> {
try {
Thread.sleep(300);
System.out.println(System.currentTimeMillis() + ": Shutdown ZK server.");
TestHelper.stopZkServer(_zkServerRef.get());
Thread.sleep(300);
System.out.println("Restart ZK server");
_zkServerRef.set(TestHelper.startZkServer(_zkAddr, null, false));
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}).get();
}
}
private List<String> createAndEnqueueJob(JobQueue.Builder queueBuild, int jobCount) {
List<String> currentJobNames = new ArrayList<>();
for (int i = 0; i < jobCount; i++) {
String targetPartition = (i == 0) ? "MASTER" : "SLAVE";
JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND)
.setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
.setTargetPartitionStates(Sets.newHashSet(targetPartition))
.setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100"));
String jobName = targetPartition.toLowerCase() + "Job" + i;
queueBuild.enqueueJob(jobName, jobConfig);
currentJobNames.add(jobName);
}
Assert.assertEquals(currentJobNames.size(), jobCount);
return currentJobNames;
}
}
| 9,489 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDisableCustomCodeRunner.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.BaseDataAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixConstants.ChangeType;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
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.InstanceConfig;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.participant.CustomCodeCallbackHandler;
import org.apache.helix.participant.HelixCustomCodeRunner;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
private static final int N = 2;
private static final int PARTITION_NUM = 1;
class DummyCallback implements CustomCodeCallbackHandler {
private final Map<NotificationContext.Type, Boolean> _callbackInvokeMap = new HashMap<>();
@Override
public void onCallback(NotificationContext context) {
NotificationContext.Type type = context.getType();
_callbackInvokeMap.put(type, Boolean.TRUE);
}
public void reset() {
_callbackInvokeMap.clear();
}
boolean isInitTypeInvoked() {
return _callbackInvokeMap.containsKey(NotificationContext.Type.INIT);
}
boolean isCallbackTypeInvoked() {
return _callbackInvokeMap.containsKey(NotificationContext.Type.CALLBACK);
}
boolean isFinalizeTypeInvoked() {
return _callbackInvokeMap.containsKey(NotificationContext.Type.FINALIZE);
}
}
@Test
public void test() 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
Map<String, MockParticipantManager> participants = new HashMap<>();
Map<String, HelixCustomCodeRunner> customCodeRunners = new HashMap<>();
Map<String, DummyCallback> callbacks = new HashMap<>();
for (int i = 0; i < N; i++) {
String instanceName = "localhost_" + (12918 + i);
participants.put(instanceName,
new MockParticipantManager(ZK_ADDR, clusterName, instanceName));
customCodeRunners.put(instanceName,
new HelixCustomCodeRunner(participants.get(instanceName), ZK_ADDR));
callbacks.put(instanceName, new DummyCallback());
customCodeRunners.get(instanceName).invoke(callbacks.get(instanceName))
.on(ChangeType.LIVE_INSTANCE).usingLeaderStandbyModel("TestParticLeader").start();
participants.get(instanceName).syncStart();
}
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName).
setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
boolean result = verifier.verifyByPolling();
Assert.assertTrue(result);
// Make sure callback is registered
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
final HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
final String customCodeRunnerResource =
customCodeRunners.get("localhost_12918").getResourceName();
String leader =
verifyCustomCodeInvoked(callbacks, accessor, keyBuilder, customCodeRunnerResource);
// Disable custom-code runner resource
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.enableResource(clusterName, customCodeRunnerResource, false);
// Verify that states of custom-code runner are all OFFLINE
result = TestHelper.verify(() -> {
PropertyKey.Builder keyBuilder1 = accessor.keyBuilder();
ExternalView extView1 =
accessor.getProperty(keyBuilder1.externalView(customCodeRunnerResource));
if (extView1 == null) {
return false;
}
Set<String> partitionSet = extView1.getPartitionSet();
if (partitionSet == null || partitionSet.size() != PARTITION_NUM) {
return false;
}
for (String partition : partitionSet) {
Map<String, String> instanceStates1 = extView1.getStateMap(partition);
for (String state : instanceStates1.values()) {
if (!"OFFLINE".equals(state)) {
return false;
}
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
// Change live-instance should not invoke any custom-code runner
String fakeInstanceName = "fakeInstance";
InstanceConfig instanceConfig = new InstanceConfig(fakeInstanceName);
instanceConfig.setHostName("localhost");
instanceConfig.setPort("10000");
instanceConfig.setInstanceEnabled(true);
admin.addInstance(clusterName, instanceConfig);
LiveInstance fakeInstance = new LiveInstance(fakeInstanceName);
fakeInstance.setSessionId("fakeSessionId");
fakeInstance.setHelixVersion("0.6");
accessor.setProperty(keyBuilder.liveInstance(fakeInstanceName), fakeInstance);
Thread.sleep(1000);
for (Map.Entry<String, DummyCallback> e : callbacks.entrySet()) {
String instance = e.getKey();
DummyCallback callback = e.getValue();
Assert.assertFalse(callback.isInitTypeInvoked());
Assert.assertFalse(callback.isCallbackTypeInvoked());
// Ensure that we were told that a leader stopped being the leader
if (instance.equals(leader)) {
Assert.assertTrue(callback.isFinalizeTypeInvoked());
}
callback.reset();
}
// Remove fake instance
accessor.removeProperty(keyBuilder.liveInstance(fakeInstanceName));
// Re-enable custom-code runner
admin.enableResource(clusterName, customCodeRunnerResource, true);
Assert.assertTrue(verifier.verifyByPolling());
// Verify that custom-invoke is invoked again
leader = verifyCustomCodeInvoked(callbacks, accessor, keyBuilder, customCodeRunnerResource);
// Add a fake instance should invoke custom-code runner
accessor.setProperty(keyBuilder.liveInstance(fakeInstanceName), fakeInstance);
Thread.sleep(1000);
for (String instance : callbacks.keySet()) {
DummyCallback callback = callbacks.get(instance);
if (instance.equals(leader)) {
Assert.assertTrue(callback.isCallbackTypeInvoked());
} else {
Assert.assertFalse(callback.isCallbackTypeInvoked());
}
}
// Clean up
controller.syncStop();
for (MockParticipantManager participant : participants.values()) {
participant.syncStop();
}
deleteLiveInstances(clusterName);
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
private String verifyCustomCodeInvoked(Map<String, DummyCallback> callbacks,
HelixDataAccessor accessor, PropertyKey.Builder keyBuilder, String customCodeRunnerResource) {
ExternalView extView = accessor.getProperty(keyBuilder.externalView(customCodeRunnerResource));
Map<String, String> instanceStates = extView.getStateMap(customCodeRunnerResource + "_0");
String leader = null;
for (String instance : instanceStates.keySet()) {
String state = instanceStates.get(instance);
if ("LEADER".equals(state)) {
leader = instance;
break;
}
}
Assert.assertNotNull(leader);
for (String instance : callbacks.keySet()) {
DummyCallback callback = callbacks.get(instance);
if (instance.equals(leader)) {
Assert.assertTrue(callback.isInitTypeInvoked() && !callback.isFinalizeTypeInvoked());
} else {
Assert.assertTrue(!callback.isInitTypeInvoked() || callback.isFinalizeTypeInvoked());
}
callback.reset();
}
return leader;
}
}
| 9,490 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDropResource.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.TestHelper;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDropResource extends ZkStandAloneCMTestBase {
@Test()
public void testDropResource() throws Exception {
// add a resource to be dropped
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "MyDB", 6, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "MyDB", 3);
boolean result =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, CLUSTER_NAME));
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.<String> setOf("localhost_12918", "localhost_12919", "localhost_12920",
"localhost_12921", "localhost_12922"), ZK_ADDR);
}
@Test()
public void testDropResourceWhileNodeDead() throws Exception {
// add a resource to be dropped
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "MyDB2", 16, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "MyDB2", 3);
boolean verifyResult =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(verifyResult);
String hostToKill = "localhost_12920";
_participants[2].syncStop();
Thread.sleep(1000);
String command = "-zkSvr " + ZK_ADDR + " -dropResource " + CLUSTER_NAME + " " + "MyDB2";
ClusterSetup.processCommandLineArgs(command.split(" "));
TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, CLUSTER_NAME, "MyDB2",
TestHelper.<String> setOf("localhost_12918", "localhost_12919",
/* "localhost_12920", */"localhost_12921", "localhost_12922"), ZK_ADDR);
_participants[2] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, hostToKill);
_participants[2].syncStart();
TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, CLUSTER_NAME, "MyDB2",
TestHelper.<String> setOf("localhost_12918", "localhost_12919", "localhost_12920",
"localhost_12921", "localhost_12922"), ZK_ADDR);
}
}
| 9,491 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestAddClusterV2.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.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.waged.WagedRebalancer;
import org.apache.helix.integration.manager.ClusterDistributedController;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.IdealState;
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.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestAddClusterV2 extends ZkTestBase {
private static final int CLUSTER_NR = 10;
protected static final int NODE_NR = 5;
protected static final int START_PORT = 12918;
protected static final String STATE_MODEL = "MasterSlave";
protected final String CLASS_NAME = getShortClassName();
private final String CONTROLLER_CLUSTER = CONTROLLER_CLUSTER_PREFIX + "_" + CLASS_NAME;
protected static final String TEST_DB = "TestDB";
MockParticipantManager[] _participants = new MockParticipantManager[NODE_NR];
private ClusterDistributedController[] _distControllers =
new ClusterDistributedController[NODE_NR];
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// setup CONTROLLER_CLUSTER
_gSetupTool.addCluster(CONTROLLER_CLUSTER, true);
for (int i = 0; i < NODE_NR; i++) {
String controllerName = CONTROLLER_PREFIX + "_" + i;
_gSetupTool.addInstanceToCluster(CONTROLLER_CLUSTER, controllerName);
}
// setup cluster of clusters
for (int i = 0; i < CLUSTER_NR; i++) {
String clusterName = CLUSTER_PREFIX + "_" + CLASS_NAME + "_" + i;
_gSetupTool.addCluster(clusterName, true);
_gSetupTool.activateCluster(clusterName, CONTROLLER_CLUSTER, true);
}
final String firstCluster = CLUSTER_PREFIX + "_" + CLASS_NAME + "_0";
setupStorageCluster(_gSetupTool, firstCluster, TEST_DB, 20, PARTICIPANT_PREFIX, START_PORT,
"MasterSlave", 3, true);
// start dummy participants for the first cluster
for (int i = 0; i < NODE_NR; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, firstCluster, instanceName);
_participants[i].syncStart();
}
// start distributed cluster controllers
for (int i = 0; i < NODE_NR; i++) {
String controllerName = CONTROLLER_PREFIX + "_" + i;
_distControllers[i] =
new ClusterDistributedController(ZK_ADDR, CONTROLLER_CLUSTER, controllerName);
_distControllers[i].syncStart();
}
verifyClusters();
}
@Test
public void Test() {
// Verify the super cluster resources are all rebalanced by the WAGED rebalancer.
HelixAdmin admin = _gSetupTool.getClusterManagementTool();
for (String clusterName : admin.getResourcesInCluster(CONTROLLER_CLUSTER)) {
IdealState is = _gSetupTool.getClusterManagementTool()
.getResourceIdealState(CONTROLLER_CLUSTER, clusterName);
Assert.assertEquals(is.getRebalancerClassName(), WagedRebalancer.class.getName());
}
}
@AfterClass
public void afterClass() throws Exception {
System.out.println("AFTERCLASS " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
/**
* shutdown order:
* 1) pause the leader (optional)
* 2) disconnect all controllers
* 3) disconnect leader/disconnect participant
*/
String leader = getCurrentLeader(_gZkClient, CONTROLLER_CLUSTER);
int leaderIdx = -1;
for (int i = 0; i < NODE_NR; i++) {
if (!_distControllers[i].getInstanceName().equals(leader)) {
_distControllers[i].syncStop();
verifyClusters();
} else {
leaderIdx = i;
}
}
Assert.assertNotSame(leaderIdx, -1);
_distControllers[leaderIdx].syncStop();
for (int i = 0; i < NODE_NR; i++) {
_participants[i].syncStop();
}
// delete clusters
for (int i = 0; i < CLUSTER_NR; i++) {
String clusterName = CLUSTER_PREFIX + "_" + CLASS_NAME + "_" + i;
deleteCluster(clusterName);
}
deleteCluster(CONTROLLER_CLUSTER);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
/**
* verify the external view (against the best possible state)
* in the controller cluster and the first cluster
*/
private void verifyClusters() {
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CONTROLLER_CLUSTER).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_PREFIX + "_" + CLASS_NAME + "_0")
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.setZkClient(_gZkClient).build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
}
protected void setupStorageCluster(ClusterSetup setupTool, String clusterName, String dbName,
int partitionNr, String prefix, int startPort, String stateModel, int replica,
boolean rebalance) {
setupTool.addResourceToCluster(clusterName, dbName, partitionNr, stateModel);
for (int i = 0; i < NODE_NR; i++) {
String instanceName = prefix + "_" + (startPort + i);
setupTool.addInstanceToCluster(clusterName, instanceName);
}
if (rebalance) {
setupTool.rebalanceStorageCluster(clusterName, dbName, replica);
}
}
}
| 9,492 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestInvalidResourceRebalance.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.Map;
import com.google.common.collect.Maps;
import org.apache.helix.HelixAdmin;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.builder.HelixConfigScopeBuilder;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestInvalidResourceRebalance extends ZkUnitTestBase {
/**
* Ensure that the Helix controller doesn't attempt to rebalance resources with invalid ideal
* states
*/
@Test
public void testResourceRebalanceSkipped() throws Exception {
final int NUM_PARTICIPANTS = 2;
final int NUM_PARTITIONS = 4;
final int NUM_REPLICAS = 2;
final String RESOURCE_NAME = "TestDB0";
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.SEMI_AUTO, // use SEMI_AUTO mode
true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// add the ideal state spec (prevents non-CUSTOMIZED MasterSlave ideal states)
HelixAdmin helixAdmin = controller.getClusterManagmentTool();
Map<String, String> properties = Maps.newHashMap();
properties.put("IdealStateRule!sampleRuleName",
"IDEAL_STATE_MODE=CUSTOMIZED,STATE_MODEL_DEF_REF=MasterSlave");
helixAdmin.setConfig(
new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(clusterName).build(),
properties);
// 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);
}
}
| 9,493 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestPartitionLevelTransitionConstraint.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.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
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.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.ClusterConstraints.ConstraintAttribute;
import org.apache.helix.model.ClusterConstraints.ConstraintType;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.model.builder.ConstraintItemBuilder;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
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 TestPartitionLevelTransitionConstraint extends ZkTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestPartitionLevelTransitionConstraint.class);
final Queue<Message> _msgOrderList = new ConcurrentLinkedQueue<Message>();
public class BootstrapStateModel extends StateModel {
public void onBecomeBootstrapFromOffline(Message message, NotificationContext context) {
LOG.info("Become Bootstrap from Offline");
_msgOrderList.add(message);
}
public void onBecomeOfflineFromBootstrap(Message message, NotificationContext context) {
LOG.info("Become Offline from Bootstrap");
_msgOrderList.add(message);
}
public void onBecomeSlaveFromBootstrap(Message message, NotificationContext context) {
LOG.info("Become Slave from Bootstrap");
_msgOrderList.add(message);
}
public void onBecomeBootstrapFromSlave(Message message, NotificationContext context) {
LOG.info("Become Bootstrap from Slave");
_msgOrderList.add(message);
}
public void onBecomeMasterFromSlave(Message message, NotificationContext context) {
LOG.info("Become Master from Slave");
_msgOrderList.add(message);
}
public void onBecomeSlaveFromMaster(Message message, NotificationContext context) {
LOG.info("Become Slave from Master");
_msgOrderList.add(message);
}
}
public class BootstrapStateModelFactory extends StateModelFactory<BootstrapStateModel> {
@Override
public BootstrapStateModel createNewStateModel(String resource, String stateUnitKey) {
BootstrapStateModel model = new BootstrapStateModel();
return model;
}
}
@Test
public void test() 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
1, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", false); // do not rebalance
// setup semi-auto ideal-state
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
StateModelDefinition stateModelDef = defineStateModel();
accessor.setProperty(accessor.keyBuilder().stateModelDef("Bootstrap"), stateModelDef);
IdealState idealState = accessor.getProperty(accessor.keyBuilder().idealStates("TestDB0"));
idealState.setStateModelDefRef("Bootstrap");
idealState.setReplicas("2");
idealState.getRecord().setListField("TestDB0_0",
Arrays.asList("localhost_12919", "localhost_12918"));
accessor.setProperty(accessor.keyBuilder().idealStates("TestDB0"), idealState);
// setup partition-level constraint
ConstraintItemBuilder constraintItemBuilder = new ConstraintItemBuilder();
constraintItemBuilder
.addConstraintAttribute(ConstraintAttribute.MESSAGE_TYPE.toString(), "STATE_TRANSITION")
.addConstraintAttribute(ConstraintAttribute.PARTITION.toString(), ".*")
.addConstraintAttribute(ConstraintAttribute.CONSTRAINT_VALUE.toString(), "1");
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.setConstraint(clusterName, ConstraintType.MESSAGE_CONSTRAINT, "constraint1",
constraintItemBuilder.build());
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start 1st participant
MockParticipantManager[] participants = new MockParticipantManager[n];
String instanceName1 = "localhost_12918";
participants[0] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName1);
participants[0].getStateMachineEngine().registerStateModelFactory("Bootstrap",
new BootstrapStateModelFactory());
participants[0].syncStart();
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
boolean result = verifier.verify();
Assert.assertTrue(result);
// start 2nd participant which will be the master for Test0_0
String instanceName2 = "localhost_12919";
participants[1] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName2);
participants[1].getStateMachineEngine().registerStateModelFactory("Bootstrap",
new BootstrapStateModelFactory());
participants[1].syncStart();
result = verifier.verify();
Assert.assertTrue(result);
// check we received the message in the right order
Assert.assertEquals(_msgOrderList.size(), 7, "_msgOrderList is:" + _msgOrderList.toString());
Message[] _msgOrderArray = _msgOrderList.toArray(new Message[0]);
assertMessage(_msgOrderArray[0], "OFFLINE", "BOOTSTRAP", instanceName1);
assertMessage(_msgOrderArray[1], "BOOTSTRAP", "SLAVE", instanceName1);
assertMessage(_msgOrderArray[2], "SLAVE", "MASTER", instanceName1);
// after we start the 2nd instance, the messages should be received in the following order:
// 1) offline->bootstrap for localhost_12919
// 2) bootstrap->slave for localhost_12919
// 3) master->slave for localhost_12918
// 4) slave->master for localhost_12919
assertMessage(_msgOrderArray[3], "OFFLINE", "BOOTSTRAP", instanceName2);
assertMessage(_msgOrderArray[4], "BOOTSTRAP", "SLAVE", instanceName2);
assertMessage(_msgOrderArray[5], "MASTER", "SLAVE", instanceName1);
assertMessage(_msgOrderArray[6], "SLAVE", "MASTER", instanceName2);
// clean up
// wait for all zk callbacks done
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
private static void assertMessage(Message msg, String fromState, String toState, String instance) {
Assert.assertEquals(msg.getFromState(), fromState);
Assert.assertEquals(msg.getToState(), toState);
Assert.assertEquals(msg.getTgtName(), instance);
}
private static StateModelDefinition defineStateModel() {
StateModelDefinition.Builder builder = new StateModelDefinition.Builder("Bootstrap");
// Add states and their rank to indicate priority. Lower the rank higher the priority
builder.addState("MASTER", 1);
builder.addState("SLAVE", 2);
builder.addState("BOOTSTRAP", 3);
builder.addState("OFFLINE");
builder.addState("DROPPED");
// Set the initial state when the node starts
builder.initialState("OFFLINE");
// Add transitions between the states.
builder.addTransition("OFFLINE", "BOOTSTRAP", 3);
builder.addTransition("BOOTSTRAP", "SLAVE", 2);
builder.addTransition("SLAVE", "MASTER", 1);
builder.addTransition("MASTER", "SLAVE", 4);
builder.addTransition("SLAVE", "OFFLINE", 5);
builder.addTransition("OFFLINE", "DROPPED", 6);
// set constraints on states.
// static constraint
builder.upperBound("MASTER", 1);
// dynamic constraint, R means it should be derived based on the replication factor.
builder.dynamicUpperBound("SLAVE", "R");
StateModelDefinition statemodelDefinition = builder.build();
assert (statemodelDefinition.isValid());
return statemodelDefinition;
}
}
| 9,494 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestSyncSessionToController.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 org.apache.helix.HelixDataAccessor;
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.ZkTestHelper;
import org.apache.helix.api.listeners.MessageListener;
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.ZKHelixManager;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.Message;
import org.apache.zookeeper.data.Stat;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestSyncSessionToController extends ZkTestBase {
@Test
public void testSyncSessionToController() throws Exception {
System.out
.println("START testSyncSessionToController at " + new Date(System.currentTimeMillis()));
String clusterName = getShortClassName();
MockParticipantManager[] participants = new MockParticipantManager[5];
int resourceNb = 10;
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
resourceNb, // resources
1, // partitions per resource
5, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
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();
}
ZKHelixManager zkHelixManager = new ZKHelixManager(clusterName, "controllerMessageListener",
InstanceType.CONTROLLER, ZK_ADDR);
zkHelixManager.connect();
MockMessageListener mockMessageListener = new MockMessageListener();
zkHelixManager.addControllerMessageListener(mockMessageListener);
PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient);
String path = keyBuilder.liveInstance("localhost_12918").getPath();
Stat stat = new Stat();
ZNRecord data = accessor.get(path, stat, 2);
data.getSimpleFields().put("SESSION_ID", "invalid-id");
accessor.set(path, data, 2);
Thread.sleep(2000);
// Since we always read the content from ephemeral nodes, sync message won't be sent
Assert.assertFalse(mockMessageListener.isSessionSyncMessageSent());
// Even after reconnect, session sync won't happen
ZkTestHelper.expireSession(participants[0].getZkClient());
Assert.assertFalse(mockMessageListener.isSessionSyncMessageSent());
// Inject an invalid session message to trigger sync message
PropertyKey messageKey = keyBuilder.message("localhost_12918", "Mocked Invalid Message");
Message msg = new Message(Message.MessageType.STATE_TRANSITION, "Mocked Invalid Message");
msg.setSrcName(controller.getInstanceName());
msg.setTgtSessionId("invalid-id");
msg.setMsgState(Message.MessageState.NEW);
msg.setMsgId("Mocked Invalid Message");
msg.setTgtName("localhost_12918");
msg.setPartitionName("foo");
msg.setResourceName("bar");
msg.setFromState("SLAVE");
msg.setToState("MASTER");
msg.setSrcSessionId(controller.getSessionId());
msg.setStateModelDef("MasterSlave");
msg.setStateModelFactoryName("DEFAULT");
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(clusterName, accessor);
dataAccessor.setProperty(messageKey, msg);
Assert.assertTrue(TestHelper.verify(() -> mockMessageListener.isSessionSyncMessageSent(), 1500));
// Cleanup
controller.syncStop();
zkHelixManager.disconnect();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
}
class MockMessageListener implements MessageListener {
private boolean sessionSyncMessageSent = false;
@Override
public void onMessage(String instanceName, List<Message> messages,
NotificationContext changeContext) {
for (Message message : messages) {
if (message.getMsgId().equals("SESSION-SYNC")) {
sessionSyncMessageSent = true;
}
}
}
boolean isSessionSyncMessageSent() {
return sessionSyncMessageSent;
}
}
}
| 9,495 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestExternalCmd.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;
import org.testng.annotations.Test;
public class TestExternalCmd {
@Test
public void testExternalCmd() 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("dummy.sh");
String output = cmd.getStringOutput("UTF8");
int idx = output.indexOf("this is a dummy test for verify ExternalCommand works");
Assert.assertNotSame(idx, -1);
System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,496 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestPauseSignal.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.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.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.PauseSignal;
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;
public class TestPauseSignal extends ZkTestBase {
@Test()
public void testPauseSignal() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
final String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
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
// start controller
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 BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// pause the cluster and make sure pause is persistent
final HelixDataAccessor tmpAccessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
String cmd = "-zkSvr " + ZK_ADDR + " -enableCluster " + clusterName + " false";
ClusterSetup.processCommandLineArgs(cmd.split(" "));
tmpAccessor.setProperty(tmpAccessor.keyBuilder().pause(), new PauseSignal("pause"));
// wait for controller to be signaled by pause
Thread.sleep(1000);
// add a new resource group
ClusterSetup setupTool = new ClusterSetup(ZK_ADDR);
setupTool.addResourceToCluster(clusterName, "TestDB1", 10, "MasterSlave");
setupTool.rebalanceStorageCluster(clusterName, "TestDB1", 3);
// make sure TestDB1 external view is empty
TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 1000, clusterName, "TestDB1",
TestHelper.setOf("localhost_12918", "localhost_12919", "localhost_12920",
"localhost_12921", "localhost_12922"),
ZK_ADDR);
// resume controller
final HelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
cmd = "-zkSvr " + ZK_ADDR + " -enableCluster " + clusterName + " true";
ClusterSetup.processCommandLineArgs(cmd.split(" "));
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,497 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestBucketizedResource.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.List;
import org.apache.helix.ExternalViewChangeListener;
import org.apache.helix.HelixAdmin;
import org.apache.helix.NotificationContext;
import org.apache.helix.NotificationContext.Type;
import org.apache.helix.PropertyKey;
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.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
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.apache.helix.tools.DefaultIdealStateCalculator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestBucketizedResource extends ZkTestBase {
private void setupCluster(String clusterName, List<String> instanceNames, String dbName,
int replica, int partitions, int bucketSize) {
_gSetupTool.addCluster(clusterName, true);
_gSetupTool.addInstancesToCluster(clusterName,
instanceNames.toArray(new String[instanceNames.size()]));
// add a bucketized resource
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ZNRecord idealStateRec =
DefaultIdealStateCalculator.calculateIdealState(instanceNames, partitions, replica - 1,
dbName,
"MASTER", "SLAVE");
IdealState idealState = new IdealState(idealStateRec);
idealState.setBucketSize(bucketSize);
idealState.setStateModelDefRef("MasterSlave");
idealState.setRebalanceMode(IdealState.RebalanceMode.CUSTOMIZED);
idealState.setReplicas(Integer.toString(replica));
accessor.setProperty(keyBuilder.idealStates(dbName), idealState);
}
@Test()
public void testBucketizedResource() {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
List<String> instanceNames =
Arrays.asList("localhost_12918", "localhost_12919", "localhost_12920", "localhost_12921", "localhost_12922");
int n = instanceNames.size();
String dbName = "TestDB0";
MockParticipantManager[] participants = new MockParticipantManager[5];
setupCluster(clusterName, instanceNames, dbName, 3, 10, 1);
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName);
controller.syncStart();
// start participants
for (int i = 0; i < n; i++) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceNames.get(i));
participants[i].syncStart();
}
PropertyKey evKey = accessor.keyBuilder().externalView(dbName);
BestPossibleExternalViewVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView ev = accessor.getProperty(evKey);
int v1 = ev.getRecord().getVersion();
// disable the participant
_gSetupTool.getClusterManagementTool().enableInstance(clusterName,
participants[0].getInstanceName(), false);
// wait for change in EV
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// read the version in EV
ev = accessor.getProperty(evKey);
int v2 = ev.getRecord().getVersion();
Assert.assertEquals(v2 > v1, true);
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
}
@Test
public void testBounceDisableAndDrop() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
String dbName = "TestDB0";
List<String> instanceNames =
Arrays.asList("localhost_0", "localhost_1", "localhost_2", "localhost_3", "localhost_4");
int n = instanceNames.size();
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
setupCluster(clusterName, instanceNames, dbName, 3, 10, 2);
// start controller
ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName);
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceNames.get(i));
participants[i].syncStart();
}
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// bounce
participants[0].syncStop();
participants[0] = new MockParticipantManager(ZK_ADDR, clusterName, instanceNames.get(0));
participants[0].syncStart();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure participants[0]'s current state is bucketzied correctly during carryover
String path =
keyBuilder.currentState(instanceNames.get(0), participants[0].getSessionId(), dbName)
.getPath();
ZNRecord record = _baseAccessor.get(path, null, 0);
Assert.assertTrue(record.getMapFields().size() == 0);
// disable the bucketize resource
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.enableResource(clusterName, dbName, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// drop the bucketize resource
_gSetupTool.dropResourceFromCluster(clusterName, dbName);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// make sure external-view is cleaned up
final String evPath = keyBuilder.externalView(dbName).getPath();
TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() {
return !_baseAccessor.exists(evPath, 0);
}
}, TestHelper.WAIT_DURATION);
boolean result = _baseAccessor.exists(evPath, 0);
Assert.assertFalse(result);
// clean up
controller.syncStop();
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
deleteCluster(clusterName);
}
class TestExternalViewListener implements ExternalViewChangeListener {
int cbCnt = 0;
@Override
public void onExternalViewChange(List<ExternalView> externalViewList,
NotificationContext changeContext) {
if (changeContext.getType() == Type.CALLBACK) {
cbCnt++;
}
}
}
@Test
public void testListenerOnBucketizedResource() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
String dbName = "TestDB0";
List<String> instanceNames =
Arrays.asList("localhost_0", "localhost_1", "localhost_2", "localhost_3", "localhost_4");
int n = instanceNames.size();
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
setupCluster(clusterName, instanceNames, dbName, 3, 10, 2);
// start controller
ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName);
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceNames.get(i));
participants[i].syncStart();
}
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// add an external view listener
final TestExternalViewListener listener = new TestExternalViewListener();
controller.addExternalViewChangeListener(listener);
// remove "TestDB0"
_gSetupTool.dropResourceFromCluster(clusterName, dbName);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// wait callback to finish
TestHelper.verify(new TestHelper.Verifier() {
@Override public boolean verify() throws Exception {
return listener.cbCnt > 0;
}
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(listener.cbCnt > 0);
listener.cbCnt = 0;
// add a new db
String newDbName = "TestDB1";
int r = 3;
ZNRecord idealStateRec =
DefaultIdealStateCalculator.calculateIdealState(instanceNames, 10, r - 1, newDbName,
"MASTER", "SLAVE");
IdealState idealState = new IdealState(idealStateRec);
idealState.setBucketSize(2);
idealState.setStateModelDefRef("MasterSlave");
idealState.setRebalanceMode(IdealState.RebalanceMode.CUSTOMIZED);
idealState.setReplicas(Integer.toString(r));
accessor.setProperty(keyBuilder.idealStates(newDbName), idealState);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
TestHelper.verify(new TestHelper.Verifier() {
@Override public boolean verify() throws Exception {
return listener.cbCnt > 0;
}
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(listener.cbCnt > 0);
// clean up
controller.syncStop();
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
deleteCluster(clusterName);
}
}
| 9,498 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestHelixCustomCodeRunner.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.HelixConstants.ChangeType;
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.participant.CustomCodeCallbackHandler;
import org.apache.helix.participant.HelixCustomCodeRunner;
import org.apache.helix.tools.ClusterStateVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestHelixCustomCodeRunner extends ZkTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestHelixCustomCodeRunner.class);
private final String _clusterName = "CLUSTER_" + getShortClassName();
private final MockCallback _callback = new MockCallback();
class MockCallback implements CustomCodeCallbackHandler {
boolean _isCallbackInvoked;
@Override
public void onCallback(NotificationContext context) {
_isCallbackInvoked = true;
// System.out.println(type + ": TestCallback invoked on " + manager.getInstanceName());
}
}
private void registerCustomCodeRunner(HelixManager manager) {
try {
// delay the start of the 1st participant
// so there will be a leadership transfer from localhost_12919 to 12918
if (manager.getInstanceName().equals("localhost_12918")) {
Thread.sleep(2000);
}
HelixCustomCodeRunner customCodeRunner = new HelixCustomCodeRunner(manager, ZK_ADDR);
customCodeRunner.invoke(_callback).on(ChangeType.LIVE_INSTANCE)
.usingLeaderStandbyModel("TestParticLeader").start();
} catch (Exception e) {
LOG.error("Exception do pre-connect job", e);
}
}
@Test
public void testCustomCodeRunner() throws Exception {
System.out.println("START " + _clusterName + " at " + new Date(System.currentTimeMillis()));
int nodeNb = 5;
int startPort = 12918;
TestHelper.setupCluster(_clusterName, ZK_ADDR, startPort, "localhost", // participant name
// prefix
"TestDB", // resource name prefix
1, // resourceNb
5, // partitionNb
nodeNb, // nodesNb
nodeNb, // replica
"MasterSlave", true);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
MockParticipantManager[] participants = new MockParticipantManager[5];
for (int i = 0; i < nodeNb; i++) {
String instanceName = "localhost_" + (startPort + i);
participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);
registerCustomCodeRunner(participants[i]);
participants[i].syncStart();
}
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName));
Assert.assertTrue(result);
Thread.sleep(1000); // wait for the INIT type callback to finish
Assert.assertTrue(_callback._isCallbackInvoked);
_callback._isCallbackInvoked = false;
// add a new live instance and its instance config.
// instance name: localhost_1000
int[] newLiveInstance = new int[]{1000};
setupInstances(_clusterName, newLiveInstance);
setupLiveInstances(_clusterName, newLiveInstance);
Thread.sleep(1000); // wait for the CALLBACK type callback to finish
Assert.assertTrue(_callback._isCallbackInvoked);
// clean up
controller.syncStop();
for (int i = 0; i < nodeNb; i++) {
participants[i].syncStop();
}
deleteLiveInstances(_clusterName);
deleteCluster(_clusterName);
System.out.println("END " + _clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.