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-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ResourceGroupsResource.java
package org.apache.helix.webapp.resources; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.helix.HelixException; import org.apache.helix.PropertyKey; import org.apache.helix.model.IdealState; import org.apache.helix.model.IdealState.RebalanceMode; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResourceGroupsResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ResourceGroupsResource.class); public ResourceGroupsResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); presentation = getHostedEntitiesRepresentation(clusterName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("Exception in get resourceGroups", e); } return presentation; } StringRepresentation getHostedEntitiesRepresentation(String clusterName) throws JsonGenerationException, JsonMappingException, IOException { // Get all resources ZkClient zkclient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.RAW_ZKCLIENT); PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName); Map<String, String> idealStateMap = ResourceUtil.readZkChildrenAsBytesMap(zkclient, keyBuilder.idealStates()); // Create the result ZNRecord hostedEntitiesRecord = new ZNRecord("ResourceGroups"); // Figure out which tags are present on which resources Map<String, String> tagMap = Maps.newHashMap(); for (String resourceName : idealStateMap.keySet()) { String idealStateStr = idealStateMap.get(resourceName); String tag = ResourceUtil.extractSimpleFieldFromZNRecord(idealStateStr, IdealState.IdealStateProperty.INSTANCE_GROUP_TAG.toString()); if (tag != null) { tagMap.put(resourceName, tag); } } // Populate the result List<String> allResources = Lists.newArrayList(idealStateMap.keySet()); hostedEntitiesRecord.setListField("ResourceGroups", allResources); if (!tagMap.isEmpty()) { hostedEntitiesRecord.setMapField("ResourceTags", tagMap); } StringRepresentation representation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(hostedEntitiesRecord), MediaType.APPLICATION_JSON); return representation; } @Override public Representation post(Representation entity) { try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); JsonParameters jsonParameters = new JsonParameters(entity); String command = jsonParameters.getCommand(); if (command.equalsIgnoreCase(ClusterSetup.addResource) || JsonParameters.CLUSTERSETUP_COMMAND_ALIASES.get(ClusterSetup.addResource).contains( command)) { jsonParameters.verifyCommand(ClusterSetup.addResource); String entityName = jsonParameters.getParameter(JsonParameters.RESOURCE_GROUP_NAME); String stateModelDefRef = jsonParameters.getParameter(JsonParameters.STATE_MODEL_DEF_REF); int partitions = Integer.parseInt(jsonParameters.getParameter(JsonParameters.PARTITIONS)); String mode = RebalanceMode.SEMI_AUTO.toString(); if (jsonParameters.getParameter(JsonParameters.IDEAL_STATE_MODE) != null) { mode = jsonParameters.getParameter(JsonParameters.IDEAL_STATE_MODE); } int bucketSize = 0; if (jsonParameters.getParameter(JsonParameters.BUCKET_SIZE) != null) { try { bucketSize = Integer.parseInt(jsonParameters.getParameter(JsonParameters.BUCKET_SIZE)); } catch (Exception e) { } } int maxPartitionsPerNode = -1; if (jsonParameters.getParameter(JsonParameters.MAX_PARTITIONS_PER_NODE) != null) { try { maxPartitionsPerNode = Integer.parseInt(jsonParameters .getParameter(JsonParameters.MAX_PARTITIONS_PER_NODE)); } catch (Exception e) { } } ZkClient zkClient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkClient); setupTool.addResourceToCluster(clusterName, entityName, partitions, stateModelDefRef, mode, bucketSize, maxPartitionsPerNode); } else { throw new HelixException("Unsupported command: " + command + ". Should be one of [" + ClusterSetup.addResource + "]"); } getResponse().setEntity(getHostedEntitiesRepresentation(clusterName)); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("Error in posting " + entity, e); } return null; } }
9,200
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/InstancesResource.java
package org.apache.helix.webapp.resources; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.collect.Lists; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.LiveInstance; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.webapp.RestAdminApplication; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InstancesResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(InstancesResource.class); public InstancesResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); presentation = getInstancesRepresentation(clusterName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("", e); } return presentation; } StringRepresentation getInstancesRepresentation(String clusterName) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); HelixDataAccessor accessor = ClusterRepresentationUtil.getClusterDataAccessor(zkClient, clusterName); Map<String, LiveInstance> liveInstancesMap = accessor.getChildValuesMap(accessor.keyBuilder().liveInstances()); Map<String, InstanceConfig> instanceConfigsMap = accessor.getChildValuesMap(accessor.keyBuilder().instanceConfigs()); Map<String, List<String>> tagInstanceLists = new TreeMap<String, List<String>>(); for (String instanceName : instanceConfigsMap.keySet()) { boolean isAlive = liveInstancesMap.containsKey(instanceName); instanceConfigsMap.get(instanceName).getRecord().setSimpleField("Alive", isAlive + ""); InstanceConfig config = instanceConfigsMap.get(instanceName); for (String tag : config.getTags()) { if (!tagInstanceLists.containsKey(tag)) { tagInstanceLists.put(tag, new LinkedList<String>()); } if (!tagInstanceLists.get(tag).contains(instanceName)) { tagInstanceLists.get(tag).add(instanceName); } } } // Wrap raw data into an object, then serialize it List<ZNRecord> recordList = Lists.newArrayList(); for (InstanceConfig instanceConfig : instanceConfigsMap.values()) { recordList.add(instanceConfig.getRecord()); } ListInstancesWrapper wrapper = new ListInstancesWrapper(); wrapper.instanceInfo = recordList; wrapper.tagInfo = tagInstanceLists; StringRepresentation representation = new StringRepresentation(ClusterRepresentationUtil.ObjectToJson(wrapper), MediaType.APPLICATION_JSON); return representation; } @Override public Representation post(Representation entity) { try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); JsonParameters jsonParameters = new JsonParameters(entity); String command = jsonParameters.getCommand(); ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkClient); if (command.equalsIgnoreCase(ClusterSetup.addInstance) || JsonParameters.CLUSTERSETUP_COMMAND_ALIASES.get(ClusterSetup.addInstance).contains( command)) { if (jsonParameters.getParameter(JsonParameters.INSTANCE_NAME) != null) { setupTool.addInstanceToCluster(clusterName, jsonParameters.getParameter(JsonParameters.INSTANCE_NAME)); } else if (jsonParameters.getParameter(JsonParameters.INSTANCE_NAMES) != null) { setupTool.addInstancesToCluster(clusterName, jsonParameters.getParameter(JsonParameters.INSTANCE_NAMES).split(";")); } else { throw new HelixException("Missing Json paramaters: '" + JsonParameters.INSTANCE_NAME + "' or '" + JsonParameters.INSTANCE_NAMES + "' "); } } else if (command.equalsIgnoreCase(ClusterSetup.swapInstance)) { if (jsonParameters.getParameter(JsonParameters.NEW_INSTANCE) == null || jsonParameters.getParameter(JsonParameters.OLD_INSTANCE) == null) { throw new HelixException("Missing Json paramaters: '" + JsonParameters.NEW_INSTANCE + "' or '" + JsonParameters.OLD_INSTANCE + "' "); } setupTool.swapInstance(clusterName, jsonParameters.getParameter(JsonParameters.OLD_INSTANCE), jsonParameters.getParameter(JsonParameters.NEW_INSTANCE)); } else { throw new HelixException("Unsupported command: " + command + ". Should be one of [" + ClusterSetup.addInstance + ", " + ClusterSetup.swapInstance + "]"); } getResponse().setEntity(getInstancesRepresentation(clusterName)); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("", e); } return null; } /** * A wrapper class for quick serialization of the data presented by this call */ public static class ListInstancesWrapper { public List<ZNRecord> instanceInfo; public Map<String, List<String>> tagInfo; } }
9,201
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/StatusUpdateResource.java
package org.apache.helix.webapp.resources; /* * 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 org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.helix.webapp.RestAdminApplication; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StatusUpdateResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(StatusUpdateResource.class); public StatusUpdateResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); String instanceName = (String) getRequest().getAttributes().get("instanceName"); String resourceGroup = (String) getRequest().getAttributes().get("resourceName"); presentation = getInstanceStatusUpdateRepresentation(clusterName, instanceName, resourceGroup); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("", e); } return presentation; } StringRepresentation getInstanceStatusUpdateRepresentation(String clusterName, String instanceName, String resourceGroup) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); Builder keyBuilder = new PropertyKey.Builder(clusterName); String message = ClusterRepresentationUtil.getInstancePropertiesAsString(zkClient, clusterName, keyBuilder.stateTransitionStatus(instanceName, instanceSessionId, resourceGroup), // instanceSessionId // + "__" // + resourceGroup, MediaType.APPLICATION_JSON); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; } }
9,202
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/JsonParameters.java
package org.apache.helix.webapp.resources; /* * 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.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.helix.HelixException; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.restlet.data.Form; import org.restlet.representation.Representation; public class JsonParameters { // json parameter key public static final String JSON_PARAMETERS = "jsonParameters"; // json parameter map keys public static final String PARTITION = "partition"; public static final String RESOURCE = "resource"; public static final String MANAGEMENT_COMMAND = "command"; public static final String ENABLED = "enabled"; public static final String GRAND_CLUSTER = "grandCluster"; public static final String REPLICAS = "replicas"; public static final String RESOURCE_KEY_PREFIX = "key"; public static final String INSTANCE_NAME = "instanceName"; public static final String INSTANCE_NAMES = "instanceNames"; public static final String OLD_INSTANCE = "oldInstance"; public static final String NEW_INSTANCE = "newInstance"; public static final String CONFIGS = "configs"; public static final String CONSTRAINT_ATTRIBUTES = "constraintAttributes"; // public static final String CONSTRAINT_ID = "constraintId"; public static final String CLUSTER_NAME = "clusterName"; public static final String PARTITIONS = "partitions"; public static final String RESOURCE_GROUP_NAME = "resourceGroupName"; public static final String STATE_MODEL_DEF_REF = "stateModelDefRef"; public static final String IDEAL_STATE_MODE = "mode"; public static final String MAX_PARTITIONS_PER_NODE = "maxPartitionsPerNode"; public static final String BUCKET_SIZE = "bucketSize"; // zk commands public static final String ZK_DELETE_CHILDREN = "zkDeleteChildren"; // extra json parameter map keys public static final String NEW_IDEAL_STATE = "newIdealState"; public static final String NEW_STATE_MODEL_DEF = "newStateModelDef"; public static final String TAG = "tag"; // aliases for ClusterSetup commands public static Map<String, Set<String>> CLUSTERSETUP_COMMAND_ALIASES; static { CLUSTERSETUP_COMMAND_ALIASES = new HashMap<String, Set<String>>(); CLUSTERSETUP_COMMAND_ALIASES.put(ClusterSetup.addResource, new HashSet<String>(Arrays.asList(new String[] { "addResourceGroup" }))); CLUSTERSETUP_COMMAND_ALIASES.put(ClusterSetup.activateCluster, new HashSet<String>(Arrays.asList(new String[] { "enableStorageCluster" }))); CLUSTERSETUP_COMMAND_ALIASES.put(ClusterSetup.addInstance, new HashSet<String>(Arrays.asList(new String[] { "addInstance" }))); } // parameter map final Map<String, String> _parameterMap; // extra parameters map final Map<String, ZNRecord> _extraParameterMap = new HashMap<String, ZNRecord>(); private static ObjectMapper mapper = new ObjectMapper(); public JsonParameters(Representation entity) throws Exception { this(new Form(entity)); } public JsonParameters(Form form) throws Exception { // get parameters in String format String jsonPayload = form.getFirstValue(JSON_PARAMETERS, true); if (jsonPayload == null || jsonPayload.isEmpty()) { _parameterMap = Collections.emptyMap(); } else { _parameterMap = ClusterRepresentationUtil.JsonToMap(jsonPayload); } // get extra parameters in ZNRecord format String newIdealStateString = form.getFirstValue(NEW_IDEAL_STATE, true); if (newIdealStateString != null) { ZNRecord newIdealState = mapper.readValue(new StringReader(newIdealStateString), ZNRecord.class); _extraParameterMap.put(NEW_IDEAL_STATE, newIdealState); } String newStateModelString = form.getFirstValue(NEW_STATE_MODEL_DEF, true); if (newStateModelString != null) { ZNRecord newStateModel = mapper.readValue(new StringReader(newStateModelString), ZNRecord.class); _extraParameterMap.put(NEW_STATE_MODEL_DEF, newStateModel); } } public String getParameter(String key) { return _parameterMap.get(key); } public String getCommand() { String command = _parameterMap.get(MANAGEMENT_COMMAND); return command; } public ZNRecord getExtraParameter(String key) { return _extraParameterMap.get(key); } public Map<String, String> cloneParameterMap() { Map<String, String> parameterMap = new TreeMap<String, String>(); parameterMap.putAll(_parameterMap); return parameterMap; } public void verifyCommand(String command) { // verify command itself if (_parameterMap.isEmpty()) { throw new HelixException("'" + JSON_PARAMETERS + "' in the POST body is empty"); } if (!_parameterMap.containsKey(MANAGEMENT_COMMAND)) { throw new HelixException("Missing management parameter '" + MANAGEMENT_COMMAND + "'"); } if (!_parameterMap.get(MANAGEMENT_COMMAND).equalsIgnoreCase(command) && !(CLUSTERSETUP_COMMAND_ALIASES.get(command) != null && CLUSTERSETUP_COMMAND_ALIASES.get( command).contains(_parameterMap.get(MANAGEMENT_COMMAND)))) { throw new HelixException(MANAGEMENT_COMMAND + " must be '" + command + "'"); } // verify command parameters if (command.equalsIgnoreCase(ClusterSetup.enableInstance)) { if (!_parameterMap.containsKey(ENABLED)) { throw new HelixException("Missing Json parameters: '" + ENABLED + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.enableResource)) { if (!_parameterMap.containsKey(ENABLED)) { throw new HelixException("Missing Json parameters: '" + ENABLED + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.enablePartition)) { if (!_parameterMap.containsKey(ENABLED)) { throw new HelixException("Missing Json parameters: '" + ENABLED + "'"); } if (!_parameterMap.containsKey(PARTITION)) { throw new HelixException("Missing Json parameters: '" + PARTITION + "'"); } if (!_parameterMap.containsKey(RESOURCE)) { throw new HelixException("Missing Json parameters: '" + RESOURCE + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.resetPartition)) { if (!_parameterMap.containsKey(PARTITION)) { throw new HelixException("Missing Json parameters: '" + PARTITION + "'"); } if (!_parameterMap.containsKey(RESOURCE)) { throw new HelixException("Missing Json parameters: '" + RESOURCE + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.resetInstance)) { // nothing } else if (command.equalsIgnoreCase(ClusterSetup.activateCluster)) { if (!_parameterMap.containsKey(GRAND_CLUSTER)) { throw new HelixException("Missing Json parameters: '" + GRAND_CLUSTER + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.setConfig)) { if (!_parameterMap.containsKey(CONFIGS)) { throw new HelixException("Missing Json parameters: '" + CONFIGS + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.removeConfig)) { if (!_parameterMap.containsKey(CONFIGS)) { throw new HelixException("Missing Json parameters: '" + CONFIGS + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.addInstanceTag)) { if (!_parameterMap.containsKey(ClusterSetup.instanceGroupTag)) { throw new HelixException("Missing Json parameters: '" + ClusterSetup.instanceGroupTag + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.removeInstanceTag)) { if (!_parameterMap.containsKey(ClusterSetup.instanceGroupTag)) { throw new HelixException("Missing Json parameters: '" + ClusterSetup.instanceGroupTag + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.addCluster)) { if (!_parameterMap.containsKey(CLUSTER_NAME)) { throw new HelixException("Missing Json parameters: '" + CLUSTER_NAME + "'"); } } else if (command.equalsIgnoreCase(ClusterSetup.addResource)) { if (!_parameterMap.containsKey(RESOURCE_GROUP_NAME)) { throw new HelixException("Missing Json parameters: '" + RESOURCE_GROUP_NAME + "'"); } if (!_parameterMap.containsKey(PARTITIONS)) { throw new HelixException("Missing Json parameters: '" + PARTITIONS + "'"); } if (!_parameterMap.containsKey(STATE_MODEL_DEF_REF)) { throw new HelixException("Missing Json parameters: '" + STATE_MODEL_DEF_REF + "'"); } } } }
9,203
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ResourceUtil.java
package org.apache.helix.webapp.resources; /* * 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.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.apache.helix.BaseDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.PropertyKey; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.webapp.RestAdminApplication; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.Context; import org.restlet.Request; import org.restlet.data.Form; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResourceUtil { private static final Logger LOG = LoggerFactory.getLogger(ResourceUtil.class); private static final ObjectMapper mapper = new ObjectMapper(); /** * Key enums for getting values from request */ public enum RequestKey { CLUSTER_NAME("clusterName"), JOB_QUEUE("jobQueue"), JOB("job"), CONSTRAINT_TYPE("constraintType"), CONSTRAINT_ID("constraintId"), RESOURCE_NAME("resourceName"), INSTANCE_NAME("instanceName"); private final String _key; RequestKey(String key) { _key = key; } public String toString() { return _key; } } /** * Key enums for getting values from context */ public enum ContextKey { ZK_ADDR(RestAdminApplication.ZKSERVERADDRESS), ZKCLIENT(RestAdminApplication.ZKCLIENT), RAW_ZKCLIENT("rawZkClient"); // zkclient that uses raw-byte serializer private final String _key; ContextKey(String key) { _key = key; } public String toString() { return _key; } } /** * Key enums for getting yaml format parameters */ public enum YamlParamKey { NEW_JOB("newJob"); private final String _key; YamlParamKey(String key) { _key = key; } public String toString() { return _key; } } private static String objectToJson(Object object) { mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); try { mapper.writeValue(sw, object); } catch (JsonGenerationException e) { // Should not be here } catch (JsonMappingException e) { // Should not be here } catch (IOException e) { // Should not be here } return sw.toString(); } public static String getAttributeFromRequest(Request r, RequestKey key) { return (String) r.getAttributes().get(key.toString()); } public static ZkClient getAttributeFromCtx(Context ctx, ContextKey key) { return (ZkClient) ctx.getAttributes().get(key.toString()); } public static String getYamlParameters(Form form, YamlParamKey key) { return form.getFirstValue(key.toString()); } public static String readZkAsBytes(ZkClient zkclient, PropertyKey propertyKey) { try { byte[] bytes = zkclient.readData(propertyKey.getPath()); return new String(bytes); } catch (Exception e) { String errorMessage = "Exception occurred when reading data from path: " + propertyKey.getPath(); LOG.error(errorMessage, e); throw new HelixException(errorMessage, e); } } static String extractSimpleFieldFromZNRecord(String recordStr, String key) { int idx = recordStr.indexOf(key); if (idx != -1) { idx = recordStr.indexOf('"', idx + key.length() + 1); if (idx != -1) { int idx2 = recordStr.indexOf('"', idx + 1); if (idx2 != -1) { return recordStr.substring(idx + 1, idx2); } } } return null; } public static Map<String, String> readZkChildrenAsBytesMap(ZkClient zkclient, PropertyKey propertyKey) { BaseDataAccessor<byte[]> baseAccessor = new ZkBaseDataAccessor<byte[]>(zkclient); String parentPath = propertyKey.getPath(); List<String> childNames = baseAccessor.getChildNames(parentPath, 0); if (childNames == null) { return null; } List<String> paths = new ArrayList<String>(); for (String childName : childNames) { paths.add(parentPath + "/" + childName); } List<byte[]> values = baseAccessor.get(paths, null, 0); Map<String, String> ret = new HashMap<String, String>(); for (int i = 0; i < childNames.size(); i++) { ret.put(childNames.get(i), new String(values.get(i))); } return ret; } }
9,204
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ZkChildResource.java
package org.apache.helix.webapp.resources; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.helix.webapp.RestAdminApplication; import org.apache.zookeeper.data.Stat; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZkChildResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ZkChildResource.class); public ZkChildResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } private String getZKPath() { String relativeRef = getRequest().getResourceRef().getRelativeRef().toString(); if (relativeRef.equals(".")) { relativeRef = ""; } // strip off trailing "/" while (relativeRef.endsWith("/")) { relativeRef = relativeRef.substring(0, relativeRef.length() - 1); } return "/" + relativeRef; } @Override public Representation get() { StringRepresentation presentation = null; String zkPath = getZKPath(); try { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ZNRecord result = readZkChild(zkPath, zkClient); presentation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(result), MediaType.APPLICATION_JSON); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("Error in read zkPath: " + zkPath, e); } return presentation; } private ZNRecord readZkChild(String zkPath, ZkClient zkClient) { ZNRecord result = null; // read data and stat Stat stat = new Stat(); ZNRecord data = zkClient.readDataAndStat(zkPath, stat, true); if (data != null) { result = data; } else { result = new ZNRecord(""); } // read childrenList List<String> children = zkClient.getChildren(zkPath); if (children != null && children.size() > 0) { result.setSimpleField("numChildren", "" + children.size()); result.setListField("childrenList", children); } else { result.setSimpleField("numChildren", "" + 0); } return result; } @Override public Representation delete() { String zkPath = getZKPath(); try { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); List<String> childNames = zkClient.getChildren(zkPath); if (childNames != null) { for (String childName : childNames) { String childPath = zkPath.equals("/") ? "/" + childName : zkPath + "/" + childName; zkClient.deleteRecursively(childPath); } } getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("Error in delete zkChild: " + zkPath, e); } return null; } }
9,205
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ClusterRepresentationUtil.java
package org.apache.helix.webapp.resources; /* * 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.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixProperty; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.PropertyType; 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.LiveInstance.LiveInstanceProperty; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.Form; import org.restlet.data.MediaType; public class ClusterRepresentationUtil { public static final ZNRecord EMPTY_ZNRECORD = new ZNRecord("EMPTY_ZNRECORD"); private static ObjectMapper mapper = new ObjectMapper(); public static String getClusterPropertyAsString(ZkClient zkClient, String clusterName, PropertyKey propertyKey, MediaType mediaType) throws JsonGenerationException, JsonMappingException, IOException { return getClusterPropertyAsString(zkClient, clusterName, mediaType, propertyKey); } public static String getClusterPropertyAsString(ZkClient zkClient, String clusterName, MediaType mediaType, PropertyKey propertyKey) throws JsonGenerationException, JsonMappingException, IOException { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); HelixProperty property = accessor.getProperty(propertyKey); ZNRecord record = property == null ? null : property.getRecord(); return ZNRecordToJson(record); } public static String getInstancePropertyNameListAsString(ZkClient zkClient, String clusterName, String instanceName, PropertyType instanceProperty, String key, MediaType mediaType) throws JsonGenerationException, JsonMappingException, IOException { String path = PropertyPathBuilder.instanceProperty(clusterName, instanceName, instanceProperty, key); if (zkClient.exists(path)) { List<String> recordNames = zkClient.getChildren(path); return ObjectToJson(recordNames); } return ObjectToJson(new ArrayList<String>()); } public static String getInstancePropertyAsString(ZkClient zkClient, String clusterName, PropertyKey propertyKey, MediaType mediaType) throws JsonGenerationException, JsonMappingException, IOException { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); ZNRecord records = accessor.getProperty(propertyKey).getRecord(); return ZNRecordToJson(records); } public static String getInstancePropertiesAsString(ZkClient zkClient, String clusterName, PropertyKey propertyKey, MediaType mediaType) throws JsonGenerationException, JsonMappingException, IOException { zkClient.setZkSerializer(new ZNRecordSerializer()); ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); List<ZNRecord> records = HelixProperty.convertToList(accessor.getChildValues(propertyKey)); return ObjectToJson(records); } public static String getPropertyAsString(ZkClient zkClient, String clusterName, PropertyKey propertyKey, MediaType mediaType) throws JsonGenerationException, JsonMappingException, IOException { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); ZNRecord record = EMPTY_ZNRECORD; HelixProperty property = accessor.getProperty(propertyKey); if (property != null) { record = property.getRecord(); } return ObjectToJson(record); } public static String ZNRecordToJson(ZNRecord record) throws JsonGenerationException, JsonMappingException, IOException { return ObjectToJson(record); } public static String ObjectToJson(Object object) throws JsonGenerationException, JsonMappingException, IOException { mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, object); return sw.toString(); } public static HelixDataAccessor getClusterDataAccessor(ZkClient zkClient, String clusterName) { return new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); } public static <T extends Object> T JsonToObject(Class<T> clazz, String jsonString) throws JsonParseException, JsonMappingException, IOException { StringReader sr = new StringReader(jsonString); return mapper.readValue(sr, clazz); } public static Map<String, String> JsonToMap(String jsonString) throws JsonParseException, JsonMappingException, IOException { StringReader sr = new StringReader(jsonString); TypeReference<TreeMap<String, String>> typeRef = new TypeReference<TreeMap<String, String>>() { }; return mapper.readValue(sr, typeRef); } public static Map<String, String> getFormJsonParameters(Form form) throws JsonParseException, JsonMappingException, IOException { String jsonPayload = form.getFirstValue(JsonParameters.JSON_PARAMETERS, true); return ClusterRepresentationUtil.JsonToMap(jsonPayload); } public static Map<String, String> getFormJsonParameters(Form form, String key) throws JsonParseException, JsonMappingException, IOException { String jsonPayload = form.getFirstValue(key, true); return ClusterRepresentationUtil.JsonToMap(jsonPayload); } public static String getFormJsonParameterString(Form form, String key) throws JsonParseException, JsonMappingException, IOException { return form.getFirstValue(key, true); } public static <T extends Object> T getFormJsonParameters(Class<T> clazz, Form form, String key) throws JsonParseException, JsonMappingException, IOException { return JsonToObject(clazz, form.getFirstValue(key, true)); } public static String getErrorAsJsonStringFromException(Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String error = e.getMessage() + '\n' + sw.toString(); Map<String, String> result = new TreeMap<String, String>(); result.put("ERROR", error); try { return ObjectToJson(result); } catch (Exception e1) { StringWriter sw1 = new StringWriter(); PrintWriter pw1 = new PrintWriter(sw1); e.printStackTrace(pw1); return "{\"ERROR\": \"" + sw1.toString() + "\"}"; } } public static String getInstanceSessionId(ZkClient zkClient, String clusterName, String instanceName) { ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient)); Builder keyBuilder = accessor.keyBuilder(); ZNRecord liveInstance = accessor.getProperty(keyBuilder.liveInstance(instanceName)).getRecord(); return liveInstance.getSimpleField(LiveInstanceProperty.SESSION_ID.toString()); } public static List<String> getInstancePropertyList(ZkClient zkClient, String clusterName, String instanceName, PropertyType property, String key) { String propertyPath = PropertyPathBuilder.instanceProperty(clusterName, instanceName, property, key); return zkClient.getChildren(propertyPath); } }
9,206
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ExternalViewResource.java
package org.apache.helix.webapp.resources; /* * 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 com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExternalViewResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ExternalViewResource.class); public ExternalViewResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); String resourceName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.RESOURCE_NAME); presentation = getExternalViewRepresentation(clusterName, resourceName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("Exception in get externalView", e); } return presentation; } StringRepresentation getExternalViewRepresentation(String clusterName, String resourceName) throws JsonGenerationException, JsonMappingException, IOException { Builder keyBuilder = new PropertyKey.Builder(clusterName); ZkClient zkclient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.RAW_ZKCLIENT); String extViewStr = ResourceUtil.readZkAsBytes(zkclient, keyBuilder.externalView(resourceName)); StringRepresentation representation = new StringRepresentation(extViewStr, MediaType.APPLICATION_JSON); return representation; } }
9,207
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ZkPathResource.java
package org.apache.helix.webapp.resources; /* * 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.HelixException; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.helix.webapp.RestAdminApplication; import org.apache.zookeeper.data.Stat; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZkPathResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ZkPathResource.class); public ZkPathResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } private String getZKPath() { String relativeRef = getRequest().getResourceRef().getRelativeRef().toString(); if (relativeRef.equals(".")) { relativeRef = ""; } // strip off trailing "/" while (relativeRef.endsWith("/")) { relativeRef = relativeRef.substring(0, relativeRef.length() - 1); } return "/" + relativeRef; } @Override public Representation post(Representation entity) { String zkPath = getZKPath(); try { JsonParameters jsonParameters = new JsonParameters(entity); String command = jsonParameters.getCommand(); ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); if (command.equalsIgnoreCase(JsonParameters.ZK_DELETE_CHILDREN)) { List<String> childNames = zkClient.getChildren(zkPath); if (childNames != null) { for (String childName : childNames) { String childPath = zkPath.equals("/") ? "/" + childName : zkPath + "/" + childName; zkClient.deleteRecursively(childPath); } } } else { throw new HelixException("Unsupported command: " + command + ". Should be one of [" + JsonParameters.ZK_DELETE_CHILDREN + "]"); } getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("Error in post zkPath: " + zkPath, e); } return null; } @Override public Representation get() { StringRepresentation presentation = null; String zkPath = getZKPath(); try { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ZNRecord result = readZkDataStatAndChild(zkPath, zkClient); presentation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(result), MediaType.APPLICATION_JSON); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("Error in read zkPath: " + zkPath, e); } return presentation; } private ZNRecord readZkDataStatAndChild(String zkPath, ZkClient zkClient) { ZNRecord result = null; // read data and stat Stat stat = new Stat(); ZNRecord data = zkClient.readDataAndStat(zkPath, stat, true); if (data != null) { result = data; } else { result = new ZNRecord(""); } result.setSimpleField("zkPath", zkPath); result.setSimpleField("stat", stat.toString()); result.setSimpleField("numChildren", "" + stat.getNumChildren()); result.setSimpleField("ctime", "" + new Date(stat.getCtime())); result.setSimpleField("mtime", "" + new Date(stat.getMtime())); result.setSimpleField("dataLength", "" + stat.getDataLength()); // read childrenList List<String> children = zkClient.getChildren(zkPath); if (children != null && children.size() > 0) { result.setListField("children", children); } return result; } @Override public Representation delete() { String zkPath = getZKPath(); try { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); zkClient.deleteRecursively(zkPath); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("Error in delete zkPath: " + zkPath, e); } return null; } }
9,208
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ClustersResource.java
package org.apache.helix.webapp.resources; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.List; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.helix.HelixException; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for server-side resource at <code> "/clusters" * <p> * <li>GET list all Helix clusters * <li>POST add a new cluster */ public class ClustersResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ClustersResource.class); public ClustersResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } /** * List all Helix clusters * <p> * Usage: <code> curl http://{host:port}/clusters */ @Override public Representation get() { StringRepresentation presentation = null; try { presentation = getClustersRepresentation(); } catch (Exception e) { LOG.error("Exception in get all clusters", e); String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); } return presentation; } StringRepresentation getClustersRepresentation() throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkClient); List<String> clusters = setupTool.getClusterManagementTool().getClusters(); ZNRecord clustersRecord = new ZNRecord("Clusters Summary"); clustersRecord.setListField("clusters", clusters); StringRepresentation representation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(clustersRecord), MediaType.APPLICATION_JSON); return representation; } /** * Add a new Helix cluster * <p> * Usage: <code> curl -d 'jsonParameters={"command":"addCluster","clusterName":"{clusterName}"}' -H * "Content-Type: application/json" http://{host:port}/clusters */ @Override public Representation post(Representation entity) { try { JsonParameters jsonParameters = new JsonParameters(entity); String command = jsonParameters.getCommand(); if (command == null) { throw new HelixException("Could NOT find 'command' in parameterMap: " + jsonParameters._parameterMap); } else if (command.equalsIgnoreCase(ClusterSetup.addCluster)) { jsonParameters.verifyCommand(ClusterSetup.addCluster); ZkClient zkClient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkClient); setupTool.addCluster(jsonParameters.getParameter(JsonParameters.CLUSTER_NAME), false); } else { throw new HelixException("Unsupported command: " + command + ". Should be one of [" + ClusterSetup.addCluster + "]"); } getResponse().setEntity(getClustersRepresentation()); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("Error in posting " + entity, e); } return null; } @Override public Representation delete() { return null; } }
9,209
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/CurrentStatesResource.java
package org.apache.helix.webapp.resources; /* * 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 com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.helix.PropertyType; import org.apache.helix.webapp.RestAdminApplication; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CurrentStatesResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(CurrentStatesResource.class); public CurrentStatesResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } public Representation get() { StringRepresentation presentation = null; try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); String instanceName = (String) getRequest().getAttributes().get("instanceName"); presentation = getInstanceCurrentStatesRepresentation(clusterName, instanceName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("", e); } return presentation; } StringRepresentation getInstanceCurrentStatesRepresentation(String clusterName, String instanceName) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ; String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); String message = ClusterRepresentationUtil .getInstancePropertyNameListAsString(zkClient, clusterName, instanceName, PropertyType.CURRENTSTATES, instanceSessionId, MediaType.APPLICATION_JSON); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; } }
9,210
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ErrorResource.java
package org.apache.helix.webapp.resources; /* * 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 com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.webapp.RestAdminApplication; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ErrorResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ErrorResource.class); public ErrorResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); String instanceName = (String) getRequest().getAttributes().get("instanceName"); String resourceGroup = (String) getRequest().getAttributes().get("resourceName"); presentation = getInstanceErrorsRepresentation(clusterName, instanceName, resourceGroup); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("", e); } return presentation; } StringRepresentation getInstanceErrorsRepresentation(String clusterName, String instanceName, String resourceGroup) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); Builder keyBuilder = new PropertyKey.Builder(clusterName); String message = ClusterRepresentationUtil.getInstancePropertiesAsString(zkClient, clusterName, keyBuilder.stateTransitionErrors(instanceName, instanceSessionId, resourceGroup), // instanceSessionId // + "__" // + resourceGroup, MediaType.APPLICATION_JSON); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; } }
9,211
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ResourceGroupResource.java
package org.apache.helix.webapp.resources; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.Arrays; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.helix.HelixException; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResourceGroupResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ResourceGroupResource.class); public ResourceGroupResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); String resourceName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.RESOURCE_NAME); presentation = getIdealStateRepresentation(clusterName, resourceName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("Exception in get resource group", e); } return presentation; } StringRepresentation getIdealStateRepresentation(String clusterName, String resourceName) throws JsonGenerationException, JsonMappingException, IOException { Builder keyBuilder = new PropertyKey.Builder(clusterName); ZkClient zkclient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.RAW_ZKCLIENT); String idealStateStr = ResourceUtil.readZkAsBytes(zkclient, keyBuilder.idealStates(resourceName)); StringRepresentation representation = new StringRepresentation(idealStateStr, MediaType.APPLICATION_JSON); return representation; } @Override public Representation delete() { try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); String resourceName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.RESOURCE_NAME); ZkClient zkclient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkclient); setupTool.dropResourceFromCluster(clusterName, resourceName); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("", e); } return null; } @Override public Representation post(Representation entity) { try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); String resourceName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.RESOURCE_NAME); ZkClient zkclient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkclient); JsonParameters jsonParameters = new JsonParameters(entity); String command = jsonParameters.getCommand(); if (command.equalsIgnoreCase(ClusterSetup.resetResource)) { setupTool.getClusterManagementTool() .resetResource(clusterName, Arrays.asList(resourceName)); } else if (command.equalsIgnoreCase(ClusterSetup.enableResource)) { jsonParameters.verifyCommand(ClusterSetup.enableResource); boolean enabled = Boolean.parseBoolean(jsonParameters.getParameter(JsonParameters.ENABLED)); setupTool.getClusterManagementTool().enableResource(clusterName, resourceName, enabled); } else { throw new HelixException("Unsupported command: " + command + ". Should be one of [" + ClusterSetup.resetResource + "]"); } } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("", e); } return null; } }
9,212
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/WorkflowsResource.java
package org.apache.helix.webapp.resources; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.collect.Lists; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.HelixProperty; import org.apache.helix.InstanceType; import org.apache.helix.PropertyKey; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.webapp.RestAdminApplication; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkflowsResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(WorkflowsResource.class); public WorkflowsResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); presentation = getHostedEntitiesRepresentation(clusterName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("", e); } return presentation; } StringRepresentation getHostedEntitiesRepresentation(String clusterName) throws JsonGenerationException, JsonMappingException, IOException { // Get all resources ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); HelixDataAccessor accessor = ClusterRepresentationUtil.getClusterDataAccessor(zkClient, clusterName); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Map<String, HelixProperty> resourceConfigMap = accessor.getChildValuesMap(keyBuilder.resourceConfigs()); // Create the result ZNRecord hostedEntitiesRecord = new ZNRecord("Workflows"); // Filter out non-workflow resources Iterator<Map.Entry<String, HelixProperty>> it = resourceConfigMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, HelixProperty> e = it.next(); HelixProperty resource = e.getValue(); Map<String, String> simpleFields = resource.getRecord().getSimpleFields(); if (!simpleFields.containsKey(WorkflowConfig.WorkflowConfigProperty.TargetState.name()) || !simpleFields.containsKey(WorkflowConfig.WorkflowConfigProperty.Dag.name())) { it.remove(); } } // Populate the result List<String> allResources = Lists.newArrayList(resourceConfigMap.keySet()); hostedEntitiesRecord.setListField("WorkflowList", allResources); StringRepresentation representation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(hostedEntitiesRecord), MediaType.APPLICATION_JSON); return representation; } @Override public Representation post(Representation entity) { try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); Form form = new Form(entity); // Get the workflow and submit it if (form.size() < 1) { throw new HelixException("yaml workflow is required!"); } Parameter payload = form.get(0); String yamlPayload = payload.getName(); if (yamlPayload == null) { throw new HelixException("yaml workflow is required!"); } String zkAddr = (String) getContext().getAttributes().get(RestAdminApplication.ZKSERVERADDRESS); HelixManager manager = HelixManagerFactory.getZKHelixManager(clusterName, null, InstanceType.ADMINISTRATOR, zkAddr); manager.connect(); try { Workflow workflow = Workflow.parse(yamlPayload); TaskDriver driver = new TaskDriver(manager); driver.start(workflow); } finally { manager.disconnect(); } getResponse().setEntity(getHostedEntitiesRepresentation(clusterName)); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("Error in posting " + entity, e); } return null; } }
9,213
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/ErrorsResource.java
package org.apache.helix.webapp.resources; /* * 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 com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.helix.PropertyType; import org.apache.helix.webapp.RestAdminApplication; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ErrorsResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(ErrorsResource.class); public ErrorsResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } public Representation get() { StringRepresentation presentation = null; try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); String instanceName = (String) getRequest().getAttributes().get("instanceName"); presentation = getInstanceErrorsRepresentation(clusterName, instanceName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("", e); } return presentation; } StringRepresentation getInstanceErrorsRepresentation(String clusterName, String instanceName) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ; String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); String message = ClusterRepresentationUtil .getInstancePropertyNameListAsString(zkClient, clusterName, instanceName, PropertyType.CURRENTSTATES, instanceSessionId, MediaType.APPLICATION_JSON); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; } }
9,214
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/CurrentStateResource.java
package org.apache.helix.webapp.resources; /* * 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 com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.webapp.RestAdminApplication; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CurrentStateResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(CurrentStateResource.class); public CurrentStateResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = (String) getRequest().getAttributes().get("clusterName"); String instanceName = (String) getRequest().getAttributes().get("instanceName"); String resourceGroup = (String) getRequest().getAttributes().get("resourceName"); presentation = getInstanceCurrentStateRepresentation(clusterName, instanceName, resourceGroup); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("", e); } return presentation; } StringRepresentation getInstanceCurrentStateRepresentation(String clusterName, String instanceName, String resourceGroup) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getRequest().getAttributes().get(RestAdminApplication.ZKCLIENT); String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); Builder keyBuilder = new PropertyKey.Builder(clusterName); String message = ClusterRepresentationUtil.getInstancePropertyAsString(zkClient, clusterName, keyBuilder.currentState(instanceName, instanceSessionId, resourceGroup), MediaType.APPLICATION_JSON); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; } }
9,215
0
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp
Create_ds/helix/helix-admin-webapp/src/main/java/org/apache/helix/webapp/resources/JobQueuesResource.java
package org.apache.helix.webapp.resources; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.collect.Lists; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.HelixProperty; import org.apache.helix.PropertyKey; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.representation.Variant; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for server-side resource at <code>"/clusters/{clusterName}/jobQueues" * <p> * <li>GET list all job queues * <li>POST add a new job queue */ public class JobQueuesResource extends ServerResource { private final static Logger LOG = LoggerFactory.getLogger(JobQueuesResource.class); public JobQueuesResource() { getVariants().add(new Variant(MediaType.TEXT_PLAIN)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); setNegotiated(false); } /** * List all job queues * <p> * Usage: <code>curl http://{host:port}/clusters/{clusterName}/jobQueues */ @Override public Representation get() { StringRepresentation presentation = null; try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); presentation = getHostedEntitiesRepresentation(clusterName); } catch (Exception e) { String error = ClusterRepresentationUtil.getErrorAsJsonStringFromException(e); presentation = new StringRepresentation(error, MediaType.APPLICATION_JSON); LOG.error("Fail to get all job queues", e); } return presentation; } StringRepresentation getHostedEntitiesRepresentation(String clusterName) throws JsonGenerationException, JsonMappingException, IOException { // Get all resources ZkClient zkClient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); HelixDataAccessor accessor = ClusterRepresentationUtil.getClusterDataAccessor(zkClient, clusterName); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Map<String, HelixProperty> resourceConfigMap = accessor.getChildValuesMap(keyBuilder.resourceConfigs()); // Create the result ZNRecord hostedEntitiesRecord = new ZNRecord("JobQueues"); // Filter out non-workflow resources Iterator<Map.Entry<String, HelixProperty>> it = resourceConfigMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, HelixProperty> e = it.next(); HelixProperty resource = e.getValue(); Map<String, String> simpleFields = resource.getRecord().getSimpleFields(); boolean isTerminable = resource.getRecord() .getBooleanField(WorkflowConfig.WorkflowConfigProperty.Terminable.name(), true); if (!simpleFields.containsKey(WorkflowConfig.WorkflowConfigProperty.TargetState.name()) || !simpleFields.containsKey(WorkflowConfig.WorkflowConfigProperty.Dag.name()) || isTerminable) { it.remove(); } } // Populate the result List<String> allResources = Lists.newArrayList(resourceConfigMap.keySet()); hostedEntitiesRecord.setListField("JobQueues", allResources); StringRepresentation representation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(hostedEntitiesRecord), MediaType.APPLICATION_JSON); return representation; } /** * Add a new job queue * <p> * Usage: * <code>curl -d @'{jobQueueConfig.yaml}' * -H 'Content-Type: application/json' http://{host:port}/clusters/{clusterName}/jobQueues * <p> * For jobQueueConfig.yaml, see {@link Workflow#parse(String)} */ @Override public Representation post(Representation entity) { try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); ZkClient zkClient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); Form form = new Form(entity); // Get the job queue and submit it if (form.size() < 1) { throw new HelixException("Yaml job queue config is required!"); } Parameter payload = form.get(0); String yamlPayload = payload.getName(); if (yamlPayload == null) { throw new HelixException("Yaml job queue config is required!"); } Workflow workflow = Workflow.parse(yamlPayload); JobQueue.Builder jobQueueCfgBuilder = new JobQueue.Builder(workflow.getName()); jobQueueCfgBuilder.fromMap(workflow.getWorkflowConfig().getResourceConfigMap()); TaskDriver driver = new TaskDriver(zkClient, clusterName); driver.createQueue(jobQueueCfgBuilder.build()); getResponse().setEntity(getHostedEntitiesRepresentation(clusterName)); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("Exception in posting job queue: " + entity, e); } return null; } }
9,216
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
package org.apache.helix.metaclient; import java.util.concurrent.TimeUnit; public class MetaClientTestUtil { public static final long WAIT_DURATION = TimeUnit.MINUTES.toMillis(1); 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(); if (result || (System.currentTimeMillis() - start) > timeout) { return result; } Thread.sleep(50); } while (true); } }
9,217
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClientCache.java
package org.apache.helix.metaclient.impl.zk; /* * 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.metaclient.MetaClientTestUtil; import org.apache.helix.metaclient.factories.MetaClientCacheConfig; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.testng.Assert; import org.testng.annotations.Test; import java.util.*; public class TestZkMetaClientCache extends ZkMetaClientTestBase { private static final String DATA_PATH = "/data"; private static final String DATA_VALUE = "testData"; @Test public void testCreateClient() { final String key = "/testCreate"; try (ZkMetaClientCache<String> zkMetaClientCache = createZkMetaClientCacheLazyCaching(key)) { zkMetaClientCache.connect(); // Perform some random non-read operation zkMetaClientCache.create(key, ENTRY_STRING_VALUE); } } @Test public void testCacheDataUpdates() { final String key = "/testCacheDataUpdates"; try (ZkMetaClientCache<String> zkMetaClientCache = createZkMetaClientCacheLazyCaching(key)) { zkMetaClientCache.connect(); zkMetaClientCache.create(key, "test"); zkMetaClientCache.create(key + DATA_PATH, DATA_VALUE); // Get data for DATA_PATH and cache it String data = zkMetaClientCache.get(key + DATA_PATH); Assert.assertEquals(data, zkMetaClientCache.getDataCacheMap().get(key + DATA_PATH)); Assert.assertTrue(MetaClientTestUtil.verify(() -> (Objects.equals(zkMetaClientCache.getDataCacheMap().get(key + DATA_PATH), data)), MetaClientTestUtil.WAIT_DURATION)); // Update data for DATA_PATH String newData = zkMetaClientCache.update(key + DATA_PATH, currentData -> currentData + "1"); Assert.assertTrue(MetaClientTestUtil.verify(() -> (Objects.equals(zkMetaClientCache.getDataCacheMap().get(key + DATA_PATH), newData)), MetaClientTestUtil.WAIT_DURATION)); zkMetaClientCache.delete(key + DATA_PATH); Assert.assertTrue(MetaClientTestUtil.verify(() -> (Objects.equals(zkMetaClientCache.getDataCacheMap().get(key + DATA_PATH), null)), MetaClientTestUtil.WAIT_DURATION)); } catch (Exception e) { throw new RuntimeException(e); } } @Test public void testGetDirectChildrenKeys() { final String key = "/testGetDirectChildrenKeys"; try (ZkMetaClientCache<String> zkMetaClientCache = createZkMetaClientCacheLazyCaching(key)) { zkMetaClientCache.connect(); zkMetaClientCache.create(key, ENTRY_STRING_VALUE); zkMetaClientCache.create(key + "/child1", ENTRY_STRING_VALUE); zkMetaClientCache.create(key + "/child2", ENTRY_STRING_VALUE); Assert.assertTrue(MetaClientTestUtil.verify(() -> (zkMetaClientCache.getDirectChildrenKeys(key).size() == 2), MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(zkMetaClientCache.getDirectChildrenKeys(key).contains("child1")); Assert.assertTrue(zkMetaClientCache.getDirectChildrenKeys(key).contains("child2")); } catch (Exception e) { throw new RuntimeException(e); } } @Test public void testCountDirectChildren() { final String key = "/testCountDirectChildren"; try (ZkMetaClientCache<String> zkMetaClientCache = createZkMetaClientCacheLazyCaching(key)) { zkMetaClientCache.connect(); zkMetaClientCache.create(key, ENTRY_STRING_VALUE); zkMetaClientCache.create(key + "/child1", ENTRY_STRING_VALUE); zkMetaClientCache.create(key + "/child2", ENTRY_STRING_VALUE); Assert.assertTrue(MetaClientTestUtil.verify(() -> ( zkMetaClientCache.countDirectChildren(key) == 2), MetaClientTestUtil.WAIT_DURATION)); } catch (Exception e) { throw new RuntimeException(e); } } @Test public void testBatchGet() { final String key = "/testBatchGet"; try (ZkMetaClientCache<String> zkMetaClientCache = createZkMetaClientCacheLazyCaching(key)) { zkMetaClientCache.connect(); zkMetaClientCache.create(key, "test"); zkMetaClientCache.create(key + DATA_PATH, DATA_VALUE); ArrayList<String> keys = new ArrayList<>(); keys.add(key); keys.add(key + DATA_PATH); ArrayList<String> values = new ArrayList<>(); values.add("test"); values.add(DATA_VALUE); Assert.assertTrue(MetaClientTestUtil.verify(() -> ( zkMetaClientCache.get(keys).equals(values)), MetaClientTestUtil.WAIT_DURATION)); } catch (Exception e) { throw new RuntimeException(e); } } @Test public void testLargeClusterLoading() { final String key = "/testLargerNodes"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); int numLayers = 4; int numNodesPerLayer = 20; // Create the root node zkMetaClient.create(key, "test"); Queue<String> queue = new LinkedList<>(); queue.offer(key); for (int layer = 1; layer <= numLayers; layer++) { int nodesAtThisLayer = Math.min(numNodesPerLayer, queue.size() * numNodesPerLayer); for (int i = 0; i < nodesAtThisLayer; i++) { String parentKey = queue.poll(); for (int j = 0; j < numNodesPerLayer; j++) { String newNodeKey = parentKey + "/node" + j; zkMetaClient.create(newNodeKey, "test"); queue.offer(newNodeKey); } } } try (ZkMetaClientCache<String> zkMetaClientCache = createZkMetaClientCacheLazyCaching(key)) { zkMetaClientCache.connect(); // Assert Checks on a Random Path Assert.assertTrue(MetaClientTestUtil.verify(() -> ( zkMetaClientCache.get(key + "/node4/node1").equals("test")), MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(MetaClientTestUtil.verify(() -> ( zkMetaClientCache.countDirectChildren(key) == numNodesPerLayer), MetaClientTestUtil.WAIT_DURATION)); String newData = zkMetaClientCache.update(key + "/node4/node1", currentData -> currentData + "1"); Assert.assertTrue(MetaClientTestUtil.verify(() -> ( zkMetaClientCache.get(key + "/node4/node1").equals(newData)), MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(MetaClientTestUtil.verify(() -> (zkMetaClientCache.getDirectChildrenKeys(key + "/node4/node1") .equals(zkMetaClient.getDirectChildrenKeys(key + "/node4/node1"))), MetaClientTestUtil.WAIT_DURATION)); zkMetaClientCache.delete(key + "/node4/node1"); Assert.assertTrue(MetaClientTestUtil.verify(() -> (Objects.equals(zkMetaClientCache.get(key + "/node4/node1"), null)), MetaClientTestUtil.WAIT_DURATION)); } catch (Exception e) { throw new RuntimeException(e); } } } public ZkMetaClientCache<String> createZkMetaClientCacheLazyCaching(String rootPath) { ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR) //.setZkSerializer(new TestStringSerializer()) .build(); MetaClientCacheConfig cacheConfig = new MetaClientCacheConfig(rootPath, true, true); return new ZkMetaClientCache<>(config, cacheConfig); } }
9,218
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
package org.apache.helix.metaclient.impl.zk; /* * 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.Date; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.io.FileUtils; import org.apache.helix.metaclient.api.ConnectStateChangeListener; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.metaclient.policy.ExponentialBackoffReconnectPolicy; import org.apache.helix.zookeeper.zkclient.IDefaultNameSpace; import org.apache.helix.zookeeper.zkclient.ZkClient; import org.apache.helix.zookeeper.zkclient.ZkServer; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.testng.Assert; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_INIT_EXP_BACKOFF_RETRY_INTERVAL_MS; import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_MAX_EXP_BACKOFF_RETRY_INTERVAL_MS; import static org.apache.helix.metaclient.impl.zk.TestUtil.*; public class TestConnectStateChangeListenerAndRetry { protected static final String ZK_ADDR = "localhost:2184"; protected static ZkServer _zkServer; @BeforeTest public void prepare() { System.out.println("START TestConnectStateChangeListenerAndRetry at " + new Date(System.currentTimeMillis())); // start local zookeeper server _zkServer = ZkMetaClientTestBase.startZkServer(ZK_ADDR); } @Test public void testConnectState() { System.out.println("STARTING TestConnectStateChangeListenerAndRetry.testConnectState at " + new Date(System.currentTimeMillis())); try (ZkMetaClient<String> zkMetaClient = createZkMetaClientReconnectTest()) { zkMetaClient.connect(); zkMetaClient.connect(); Assert.fail("The second connect should throw IllegalStateException"); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalStateException); Assert.assertEquals(ex.getMessage(), "ZkClient is not in init state. connect() has already been called."); } System.out.println("END TestConnectStateChangeListenerAndRetry.testConnectState at " + new Date(System.currentTimeMillis())); } // test mock zkclient event @Test(dependsOnMethods = "testConnectState") public void testReConnectSucceed() throws InterruptedException { System.out.println("STARTING TestConnectStateChangeListenerAndRetry.testReConnectSucceed at " + new Date(System.currentTimeMillis())); try (ZkMetaClient<String> zkMetaClient = createZkMetaClientReconnectTest()) { CountDownLatch countDownLatch = new CountDownLatch(1); zkMetaClient.connect(); // We need a separate thread to simulate reconnect. In ZkClient there is assertion to check // reconnect and and CRUDs are not in the same thread. (So one does not block another) Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { try { simulateZkStateReconnected(zkMetaClient); } catch (InterruptedException e) { Assert.fail("Exception in simulateZkStateReconnected", e); } countDownLatch.countDown(); } }); countDownLatch.await(5000, TimeUnit.SECONDS); Thread.sleep(AUTO_RECONNECT_WAIT_TIME_EXD); // When ZK reconnect happens within timeout window, zkMetaClient should ba able to perform CRUD. Assert.assertTrue(zkMetaClient.getZkClient().getConnection().getZookeeperState().isConnected()); zkMetaClient.create("/key", "value"); Assert.assertEquals(zkMetaClient.get("/key"), "value"); } System.out.println("END TestConnectStateChangeListenerAndRetry.testReConnectSucceed at " + new Date(System.currentTimeMillis())); } @Test(dependsOnMethods = "testReConnectSucceed") public void testConnectStateChangeListener() throws Exception { System.out.println("START TestConnectStateChangeListenerAndRetry.testConnectStateChangeListener at " + new Date(System.currentTimeMillis())); try (ZkMetaClient<String> zkMetaClient = createZkMetaClientReconnectTest()) { CountDownLatch countDownLatch = new CountDownLatch(1); final MetaClientInterface.ConnectState[] connectState = new MetaClientInterface.ConnectState[2]; ConnectStateChangeListener listener = new ConnectStateChangeListener() { @Override public void handleConnectStateChanged(MetaClientInterface.ConnectState prevState, MetaClientInterface.ConnectState currentState) throws Exception { connectState[0] = prevState; connectState[1] = currentState; countDownLatch.countDown(); } @Override public void handleConnectionEstablishmentError(Throwable error) throws Exception { } }; Assert.assertTrue(zkMetaClient.subscribeStateChanges(listener)); zkMetaClient.connect(); countDownLatch.await(5000, TimeUnit.SECONDS); Assert.assertEquals(connectState[0], MetaClientInterface.ConnectState.NOT_CONNECTED); Assert.assertEquals(connectState[1], MetaClientInterface.ConnectState.CONNECTED); _zkServer.shutdown(); Thread.sleep(AUTO_RECONNECT_WAIT_TIME_EXD); Assert.assertEquals(connectState[0], MetaClientInterface.ConnectState.CONNECTED); Assert.assertEquals(connectState[1], MetaClientInterface.ConnectState.DISCONNECTED); try { zkMetaClient.create("/key", "value"); Assert.fail("Create call after close should throw IllegalStateException"); } catch (Exception ex) { Assert.assertTrue(ex instanceof IllegalStateException); } zkMetaClient.unsubscribeConnectStateChanges(listener); } System.out.println("END TestConnectStateChangeListenerAndRetry.testConnectStateChangeListener at " + new Date(System.currentTimeMillis())); } static ZkMetaClient<String> createZkMetaClientReconnectTest() { ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR) .setMetaClientReconnectPolicy( new ExponentialBackoffReconnectPolicy( AUTO_RECONNECT_TIMEOUT_MS_FOR_TEST)) .build(); return new ZkMetaClient<>(config); } }
9,219
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClientAsyncOperations.java
package org.apache.helix.metaclient.impl.zk; /* * 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.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.apache.helix.metaclient.api.AsyncCallback; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.zookeeper.KeeperException; import org.testng.Assert; import org.testng.annotations.Test; public class TestZkMetaClientAsyncOperations extends ZkMetaClientTestBase { static TestAsyncContext[] asyncContext = new TestAsyncContext[1]; static final String entryKey = "/TestAsyncEntryKey"; static final String nonExistsEntry = "/a/b/c"; static final long LATCH_WAIT_TIMEOUT_IN_S = 3 * 60; static class TestAsyncContext { int _asyncCallSize; CountDownLatch _countDownLatch; int[] _returnCode; MetaClientInterface.Stat[] _stats; String[] _data; TestAsyncContext(int callSize) { _asyncCallSize = callSize; _countDownLatch = new CountDownLatch(callSize); _returnCode = new int[callSize]; _stats = new MetaClientInterface.Stat[callSize]; _data = new String[callSize]; } public CountDownLatch getCountDownLatch() { return _countDownLatch; } public void countDown() { _countDownLatch.countDown(); } public int getReturnCode(int idx) { return _returnCode[idx]; } public MetaClientInterface.Stat getStats(int idx) { return _stats[idx]; } public String getData(int idx) { return _data[idx]; } public void setReturnCodeWhenFinished(int idx, int returnCode) { _returnCode[idx] = returnCode; } public void setStatWhenFinished(int idx, MetaClientInterface.Stat stat) { _stats[idx] = stat; } public void setDataWhenFinished(int idx, String data) { _data[idx] = data; } } @Test public void testAsyncCreateSetAndGet() { asyncContext[0] = new TestAsyncContext(2); try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient .asyncCreate(entryKey, "async_create-data", MetaClientInterface.EntryMode.PERSISTENT, new AsyncCallback.VoidCallback() { @Override public void processResult(int returnCode, String key) { asyncContext[0].setReturnCodeWhenFinished(0, returnCode); asyncContext[0].countDown(); } }); zkMetaClient.asyncCreate(nonExistsEntry, "async_create-data-invalid", MetaClientInterface.EntryMode.PERSISTENT, new AsyncCallback.VoidCallback() { @Override public void processResult(int returnCode, String key) { asyncContext[0].setReturnCodeWhenFinished(1, returnCode); asyncContext[0].countDown(); } }); asyncContext[0].getCountDownLatch().await(LATCH_WAIT_TIMEOUT_IN_S, TimeUnit.SECONDS); Assert.assertEquals(asyncContext[0].getReturnCode(0), KeeperException.Code.OK.intValue()); Assert.assertEquals(asyncContext[0].getReturnCode(1), KeeperException.Code.NONODE.intValue()); // create the entry again and expect a duplicated error code asyncContext[0] = new TestAsyncContext(1); zkMetaClient .asyncCreate(entryKey, "async_create-data", MetaClientInterface.EntryMode.PERSISTENT, new AsyncCallback.VoidCallback() { @Override public void processResult(int returnCode, String key) { asyncContext[0].setReturnCodeWhenFinished(0, returnCode); asyncContext[0].countDown(); } }); asyncContext[0].getCountDownLatch().await(LATCH_WAIT_TIMEOUT_IN_S, TimeUnit.SECONDS); Assert.assertEquals(asyncContext[0].getReturnCode(0), KeeperException.Code.NODEEXISTS.intValue()); // test set asyncContext[0] = new TestAsyncContext(1); zkMetaClient .asyncSet(entryKey, "async_create-data-new", 0, new AsyncCallback.StatCallback() { @Override public void processResult(int returnCode, String key, @Nullable MetaClientInterface.Stat stat) { asyncContext[0].setReturnCodeWhenFinished(0, returnCode); asyncContext[0].setStatWhenFinished(0, stat); asyncContext[0].countDown(); } }); asyncContext[0].getCountDownLatch().await(LATCH_WAIT_TIMEOUT_IN_S, TimeUnit.SECONDS); Assert.assertEquals(asyncContext[0].getReturnCode(0), KeeperException.Code.OK.intValue()); Assert.assertEquals(asyncContext[0].getStats(0).getEntryType(), MetaClientInterface.EntryMode.PERSISTENT); Assert.assertEquals(asyncContext[0].getStats(0).getVersion(), 1); // test get asyncContext[0] = new TestAsyncContext(1); zkMetaClient.asyncGet(entryKey, new AsyncCallback.DataCallback() { @Override public void processResult(int returnCode, String key, byte[] data, MetaClientInterface.Stat stat) { asyncContext[0].setReturnCodeWhenFinished(0, returnCode); asyncContext[0].setStatWhenFinished(0, stat); asyncContext[0].setDataWhenFinished(0, zkMetaClient.deserialize(data, key)); asyncContext[0].countDown(); } }); asyncContext[0].getCountDownLatch().await(LATCH_WAIT_TIMEOUT_IN_S, TimeUnit.SECONDS); Assert.assertEquals(asyncContext[0].getReturnCode(0), KeeperException.Code.OK.intValue()); Assert.assertEquals(asyncContext[0].getStats(0).getEntryType(), MetaClientInterface.EntryMode.PERSISTENT); Assert.assertEquals(asyncContext[0].getStats(0).getVersion(), 1); Assert.assertEquals(asyncContext[0].getData(0), "async_create-data-new"); } catch (Exception ex) { Assert.fail("Test testAsyncCreate failed because of:", ex); } } @Test(dependsOnMethods = "testAsyncCreateSetAndGet") public void testAsyncExistsAndDelete() { asyncContext[0] = new TestAsyncContext(2); try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.asyncExist(entryKey, new AsyncCallback.StatCallback() { @Override public void processResult(int returnCode, String key, MetaClientInterface.Stat stat) { asyncContext[0].setReturnCodeWhenFinished(0, returnCode); asyncContext[0].setStatWhenFinished(0, stat); asyncContext[0].countDown(); } }); zkMetaClient.asyncExist(nonExistsEntry, new AsyncCallback.StatCallback() { @Override public void processResult(int returnCode, String key, MetaClientInterface.Stat stat) { asyncContext[0].setReturnCodeWhenFinished(1, returnCode); asyncContext[0].setStatWhenFinished(1, stat); asyncContext[0].countDown(); } }); asyncContext[0].getCountDownLatch().await(LATCH_WAIT_TIMEOUT_IN_S, TimeUnit.SECONDS); Assert.assertEquals(asyncContext[0].getReturnCode(0), KeeperException.Code.OK.intValue()); Assert.assertEquals(asyncContext[0].getStats(0).getEntryType(), MetaClientInterface.EntryMode.PERSISTENT); Assert.assertEquals(asyncContext[0].getStats(0).getVersion(), 1); Assert.assertEquals(asyncContext[0].getReturnCode(1), KeeperException.Code.NONODE.intValue()); Assert.assertNull(asyncContext[0].getStats(1)); // test delete asyncContext[0] = new TestAsyncContext(1); zkMetaClient.asyncDelete(entryKey, new AsyncCallback.VoidCallback() { @Override public void processResult(int returnCode, String key) { asyncContext[0].setReturnCodeWhenFinished(0, returnCode); asyncContext[0].countDown(); } }); asyncContext[0].getCountDownLatch().await(LATCH_WAIT_TIMEOUT_IN_S, TimeUnit.SECONDS); Assert.assertEquals(asyncContext[0].getReturnCode(0), KeeperException.Code.OK.intValue()); // node should not be there Assert.assertNull(zkMetaClient.get(entryKey)); } catch (InterruptedException ex) { Assert.fail("Test testAsyncCreate failed because of:", ex); } } }
9,220
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
package org.apache.helix.metaclient.impl.zk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.helix.metaclient.api.*; import org.apache.helix.metaclient.datamodel.DataRecord; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.exception.MetaClientNodeExistsException; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.metaclient.recipes.lock.DataRecordSerializer; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.apache.helix.metaclient.api.MetaClientInterface.EntryMode.*; public class TestStressZkClient extends ZkMetaClientTestBase { private ZkMetaClient<String> _zkMetaClient; private static final long TEST_ITERATION_COUNT = 500; @BeforeTest private void setUp() { this._zkMetaClient = createZkMetaClient(); this._zkMetaClient.connect(); } @AfterTest @Override public void cleanUp() { this._zkMetaClient.close(); } @Test public void testCreate() { String zkParentKey = "/stressZk_testCreate"; _zkMetaClient.create(zkParentKey, "parent_node"); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.create(zkParentKey + "/" + i, i); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertEquals(String.valueOf(_zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i)); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { try { _zkMetaClient.create("/a/b/c", "invalid_path"); Assert.fail("Should have failed with incorrect path."); } catch (MetaClientException ignoredException) { } } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { try { _zkMetaClient.create("a/b/c", "invalid_path"); Assert.fail("Should have failed with invalid path - no leading /."); } catch (Exception ignoredException) { } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } } @Test public void testCreateContainer() { final String zkParentKey = "/stressZk_testCreateContainer"; _zkMetaClient.create(zkParentKey, "parent_node"); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.create(zkParentKey + "/" + i, i, CONTAINER); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertEquals(String.valueOf(_zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i)); } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testCreateAndRenewTTL() { final String zkParentKey = "/stressZk_testCreateAndRenewTTL"; _zkMetaClient.create(zkParentKey, ENTRY_STRING_VALUE); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.createWithTTL(zkParentKey + i, ENTRY_STRING_VALUE, 10000); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertNotNull(_zkMetaClient.exists(zkParentKey)); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.renewTTLNode(zkParentKey + i); } MetaClientInterface.Stat stat; for (int i = 0; i < TEST_ITERATION_COUNT; i++) { stat = _zkMetaClient.exists(zkParentKey + i); Assert.assertNotSame(stat.getCreationTime(), stat.getModifiedTime()); } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testRecursiveCreate() { final String zkParentKey = "/stressZk_testRecursiveCreate"; _zkMetaClient.create(zkParentKey, ENTRY_STRING_VALUE); int count = (int) Math.pow(TEST_ITERATION_COUNT, 1/3d); for (int i = 0; i < count; i++) { for (int j = 0; j < count; j++) { for (int k = 0; k < count; k++) { String key = zkParentKey + "/" + i + "/" + j + "/" + k; _zkMetaClient.recursiveCreate(key, String.valueOf(k), PERSISTENT); Assert.assertEquals(String.valueOf(k), _zkMetaClient.get(key)); } } try { _zkMetaClient.recursiveCreate(zkParentKey + "/" + i, "should_fail", PERSISTENT); Assert.fail("Should have failed due to node existing"); } catch (MetaClientNodeExistsException ignoredException) { } } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testGet() { final String zkParentKey = "/stressZk_testGet"; _zkMetaClient.create(zkParentKey, "parent_node"); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.create(zkParentKey + "/" + i, i); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertEquals(_zkMetaClient.get(zkParentKey + "/" + i), i); } // Test with non-existent node path for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertNull(_zkMetaClient.get("/a/b/c")); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { try { _zkMetaClient.get("a/b/c"); Assert.fail("Should have failed due to invalid path - no leading /."); } catch (Exception ignoredException) { } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } } @Test public void testSetSingleNode() { final String zkParentKey = "/stressZk_testSetSingleNode"; _zkMetaClient.create(zkParentKey, "parent_node"); // Set with no expected version for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.set(zkParentKey, String.valueOf(i), -1); MetaClientInterface.Stat entryStat = _zkMetaClient.exists(zkParentKey); Assert.assertEquals(_zkMetaClient.get(zkParentKey), String.valueOf(i)); Assert.assertEquals(entryStat.getVersion(), i + 1); Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name()); } _zkMetaClient.delete(zkParentKey); _zkMetaClient.create(zkParentKey, "parent_node"); // Set with expected version for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.set(zkParentKey, String.valueOf(i), i); MetaClientInterface.Stat entryStat = _zkMetaClient.exists(zkParentKey); Assert.assertEquals(_zkMetaClient.get(zkParentKey), String.valueOf(i)); Assert.assertEquals(entryStat.getVersion(), i + 1); } _zkMetaClient.delete(zkParentKey); _zkMetaClient.create(zkParentKey, "parent_node"); // Set with bad expected version - should fail for (int i = 0; i < TEST_ITERATION_COUNT; i++) { try { _zkMetaClient.set(zkParentKey, "test-should-fail", 12345); Assert.fail("Should have failed due to bad expected version in set function."); } catch (MetaClientException ex) { Assert.assertEquals(ex.getClass().getName(), "org.apache.helix.metaclient.exception.MetaClientBadVersionException"); } } _zkMetaClient.delete(zkParentKey); _zkMetaClient.create(zkParentKey, "parent_node"); // Set with path to non-existent node - should fail for (int i = 0; i < TEST_ITERATION_COUNT; i++) { try { _zkMetaClient.set("/a/b/c", "test-should-fail", -1); Assert.fail("Should have failed due to path to non-existent node"); } catch (Exception ignoredException) { } } _zkMetaClient.delete(zkParentKey); _zkMetaClient.create(zkParentKey, "parent_node"); // Set with invalid path - should fail for (int i = 0; i < TEST_ITERATION_COUNT; i++) { try { _zkMetaClient.set("a/b/c", "test-should-fail", -1); Assert.fail("Should have failed due to invalid path - no leading /."); } catch (Exception ignoredException) { } } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testSetMultiNode() { final String zkParentKey = "/stressZk_testSetMultiNode"; _zkMetaClient.create(zkParentKey, "parent_node"); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.create(zkParentKey + "/" + i, i); } // Set with no expected version for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.set(zkParentKey + "/" + i, "-" + i, -1); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { String childKey = zkParentKey + "/" + i; MetaClientInterface.Stat entryStat = _zkMetaClient.exists(childKey); Assert.assertEquals(_zkMetaClient.get(childKey), "-" + i); Assert.assertEquals(entryStat.getVersion(), 1); Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name()); } // Set with expected version for (int i = 0; i < TEST_ITERATION_COUNT; i++) { String childKey = zkParentKey + "/" + i; _zkMetaClient.set(childKey, String.valueOf(i), 1); MetaClientInterface.Stat entryStat = _zkMetaClient.exists(childKey); Assert.assertEquals(_zkMetaClient.get(childKey), String.valueOf(i)); Assert.assertEquals(entryStat.getVersion(), 2); } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testUpdateSingleNode() { final String zkParentKey = "/stressZk_testUpdateSingleNode"; ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR) .setZkSerializer(new DataRecordSerializer()).build(); try (ZkMetaClient<DataRecord> zkMetaClient = new ZkMetaClient<>(config)) { zkMetaClient.connect(); DataRecord record = new DataRecord(zkParentKey); record.setIntField("key", 0); zkMetaClient.create(zkParentKey, record); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey); Assert.assertEquals(entryStat.getVersion(), i); DataRecord newData = zkMetaClient.update(zkParentKey, new DataUpdater<DataRecord>() { @Override public DataRecord update(DataRecord currentData) { int value = currentData.getIntField("key", 0); currentData.setIntField("key", value + 1); return currentData; } }); Assert.assertEquals(newData.getIntField("key", 0), i+1); } // cleanup zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0); } } @Test public void testUpdateMultiNode() { final String zkParentKey = "/stressZk_testUpdateMultiNode"; ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR) .setZkSerializer(new DataRecordSerializer()).build(); try (ZkMetaClient<DataRecord> zkMetaClient = new ZkMetaClient<>(config)) { zkMetaClient.connect(); DataRecord parentRecord = new DataRecord(zkParentKey); zkMetaClient.create(zkParentKey, parentRecord); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { String childKey = zkParentKey + "/" + i; DataRecord record = new DataRecord(childKey); record.setIntField("key", 0); zkMetaClient.create(childKey, record); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { String childKey = zkParentKey + "/" + i; MetaClientInterface.Stat entryStat = zkMetaClient.exists(childKey); Assert.assertEquals(entryStat.getVersion(), 0); DataRecord newData = zkMetaClient.update(childKey, new DataUpdater<DataRecord>() { @Override public DataRecord update(DataRecord currentData) { int value = currentData.getIntField("key", 0); currentData.setIntField("key", value + 1); return currentData; } }); Assert.assertEquals(newData.getIntField("key",0), 1); entryStat = zkMetaClient.exists(childKey); Assert.assertEquals(entryStat.getVersion(), 1); } // cleanup zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0); } } @Test public void testMultipleDataChangeListeners() throws Exception { final String zkParentKey = "/stressZk_testMultipleDataChangeListeners"; final int listenerCount = 10; final String testData = "test-data"; final AtomicBoolean dataExpected = new AtomicBoolean(true); _zkMetaClient.create(zkParentKey, "parent_node"); CountDownLatch countDownLatch = new CountDownLatch((int) TEST_ITERATION_COUNT * listenerCount); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.create(zkParentKey + "/" + i, i); } // create paths for (int i = 0; i < TEST_ITERATION_COUNT; i++) { String childKey = zkParentKey + "/" + i; for (int j = 0; j < listenerCount; j++) { DataChangeListener listener = new DataChangeListener() { @Override public void handleDataChange(String key, Object data, ChangeType changeType) { countDownLatch.countDown(); dataExpected.set(dataExpected.get() && testData.equals(data)); } }; _zkMetaClient.subscribeDataChange(childKey, listener, false); } } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { _zkMetaClient.set(zkParentKey + "/" + i, testData, -1); } Assert.assertTrue(countDownLatch.await(5000, TimeUnit.MILLISECONDS)); Assert.assertTrue(dataExpected.get()); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testTransactionOps() { String zkParentKey = "/stressZk_testTransactionOp"; _zkMetaClient.create(zkParentKey, "parent_node"); // Transaction Create List<Op> ops = new ArrayList<>(); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { ops.add(Op.create(zkParentKey + "/" + i, new byte[0], PERSISTENT)); } List<OpResult> opResults = _zkMetaClient.transactionOP(ops); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertTrue(opResults.get(i) instanceof OpResult.CreateResult); } for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertNotNull(_zkMetaClient.exists(zkParentKey + "/" + i)); } // Transaction Set List<Op> ops_set = new ArrayList<>(); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { ops_set.add(Op.set(zkParentKey + "/" + i, new byte[0], -1)); } List<OpResult> opsResultSet = _zkMetaClient.transactionOP(ops_set); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertTrue(opsResultSet.get(i) instanceof OpResult.SetDataResult); } // Transaction Delete List<Op> ops_delete = new ArrayList<>(); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { ops_delete.add(Op.delete(zkParentKey + "/" + i, -1)); } List<OpResult> opsResultDelete = _zkMetaClient.transactionOP(ops_delete); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { Assert.assertTrue(opsResultDelete.get(i) instanceof OpResult.DeleteResult); } // Transaction Create List<Op> ops_error = new ArrayList<>(); for (int i = 0; i < TEST_ITERATION_COUNT; i++) { ops_error.add(Op.create("/_invalid/a/b/c" + "/" + i, new byte[0], PERSISTENT)); } try { _zkMetaClient.transactionOP(ops_error); Assert.fail("Should fail"); } catch (Exception e) { // OK } // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } }
9,221
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java
package org.apache.helix.metaclient.impl.zk; /* * 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.commons.lang3.tuple.ImmutablePair; import org.apache.helix.metaclient.api.ChildChangeListener; import org.apache.helix.metaclient.api.DataUpdater; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.api.DirectChildChangeListener; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.NotImplementedException; import org.apache.helix.metaclient.api.DataChangeListener; import org.apache.helix.metaclient.api.Op; import org.apache.helix.metaclient.api.OpResult; import org.apache.helix.metaclient.exception.MetaClientNoNodeException; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.zookeeper.KeeperException; import org.testng.Assert; import org.testng.annotations.Test; import static org.apache.helix.metaclient.api.DataChangeListener.ChangeType.ENTRY_UPDATE; import static org.apache.helix.metaclient.api.MetaClientInterface.EntryMode.CONTAINER; import static org.apache.helix.metaclient.api.MetaClientInterface.EntryMode.EPHEMERAL; import static org.apache.helix.metaclient.api.MetaClientInterface.EntryMode.PERSISTENT; public class TestZkMetaClient extends ZkMetaClientTestBase{ private static final String TRANSACTION_TEST_PARENT_PATH = "/transactionOpTestPath"; private static final String TEST_INVALID_PATH = "/_invalid/a/b/c"; private static final int DEFAULT_LISTENER_WAIT_TIMEOUT = 5000; private final Object _syncObject = new Object(); @Test public void testCreate() { final String key = "/TestZkMetaClient_testCreate"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.create(key, ENTRY_STRING_VALUE); Assert.assertNotNull(zkMetaClient.exists(key)); try { zkMetaClient.create("a/b/c", "invalid_path"); Assert.fail("Should have failed with incorrect path."); } catch (Exception ignored) { } } } @Test public void testCreateContainer() { final String key = "/TestZkMetaClient_testCreateContainer"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.create(key, ENTRY_STRING_VALUE, CONTAINER); Assert.assertNotNull(zkMetaClient.exists(key)); } } @Test public void testCreateTTL() { final String key = "/TestZkMetaClient_testTTL"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.createWithTTL(key, ENTRY_STRING_VALUE, 1000); Assert.assertNotNull(zkMetaClient.exists(key)); } } @Test public void testRecursiveCreate() { final String path = "/Test/ZkMetaClient/_fullPath"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); MetaClientInterface.EntryMode mode = EPHEMERAL; // Should succeed even if one of the parent nodes exists String extendedPath = "/A" + path; zkMetaClient.create("/A", ENTRY_STRING_VALUE, PERSISTENT); zkMetaClient.recursiveCreate(extendedPath, ENTRY_STRING_VALUE, mode); Assert.assertNotNull(zkMetaClient.exists(extendedPath)); // Should succeed if no parent nodes exist zkMetaClient.recursiveCreate(path, ENTRY_STRING_VALUE, mode); Assert.assertNotNull(zkMetaClient.exists(path)); Assert.assertEquals(zkMetaClient.getDataAndStat("/Test").getRight().getEntryType(), PERSISTENT); Assert.assertEquals(zkMetaClient.getDataAndStat(path).getRight().getEntryType(), mode); // Should throw NodeExistsException if child node exists zkMetaClient.recursiveCreate(path, ENTRY_STRING_VALUE, mode); Assert.fail("Should have failed due to node already created"); } catch (MetaClientException e) { Assert.assertEquals(e.getMessage(), "org.apache.helix.zookeeper.zkclient.exception.ZkNodeExistsException: org.apache.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /Test/ZkMetaClient/_fullPath"); System.out.println(e.getMessage()); } } @Test public void testRecursiveCreateWithTTL() { final String path = "/Test/ZkMetaClient/_fullPath/withTTL"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.recursiveCreateWithTTL(path, ENTRY_STRING_VALUE, 1000); Assert.assertNotNull(zkMetaClient.exists(path)); } } @Test public void testRenewTTL() { final String key = "/TestZkMetaClient_testRenewTTL_1"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.createWithTTL(key, ENTRY_STRING_VALUE, 10000); Assert.assertNotNull(zkMetaClient.exists(key)); MetaClientInterface.Stat stat = zkMetaClient.exists(key); zkMetaClient.renewTTLNode(key); // Renewing a ttl node changes the nodes modified_time. Should be different // from the time the node was created. Assert.assertNotSame(stat.getCreationTime(), stat.getModifiedTime()); try { zkMetaClient.renewTTLNode(TEST_INVALID_PATH); } catch (MetaClientNoNodeException ignored) { } } } @Test public void testGet() { final String key = "/TestZkMetaClient_testGet"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); String value; zkMetaClient.create(key, ENTRY_STRING_VALUE); String dataValue = zkMetaClient.get(key); Assert.assertEquals(dataValue, ENTRY_STRING_VALUE); value = zkMetaClient.get(key + "/a/b/c"); Assert.assertNull(value); zkMetaClient.delete(key); value = zkMetaClient.get(key); Assert.assertNull(value); } } @Test public void testSet() { final String key = "/TestZkMetaClient_testSet"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.create(key, ENTRY_STRING_VALUE); String testValueV1 = ENTRY_STRING_VALUE + "-v1"; String testValueV2 = ENTRY_STRING_VALUE + "-v2"; // test set() with no expected version and validate result. zkMetaClient.set(key, testValueV1, -1); Assert.assertEquals(zkMetaClient.get(key), testValueV1); MetaClientInterface.Stat entryStat = zkMetaClient.exists(key); Assert.assertEquals(entryStat.getVersion(), 1); Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name()); // test set() with expected version and validate result and new version number zkMetaClient.set(key, testValueV2, 1); entryStat = zkMetaClient.exists(key); Assert.assertEquals(zkMetaClient.get(key), testValueV2); Assert.assertEquals(entryStat.getVersion(), 2); // test set() with a wrong version try { zkMetaClient.set(key, "test-node-changed", 10); Assert.fail("No reach."); } catch (MetaClientException ex) { Assert.assertEquals(ex.getClass().getName(), "org.apache.helix.metaclient.exception.MetaClientBadVersionException"); } zkMetaClient.delete(key); } } @Test public void testUpdate() { final String key = "/TestZkMetaClient_testUpdate"; ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build(); try (ZkMetaClient<Integer> zkMetaClient = new ZkMetaClient<>(config)) { zkMetaClient.connect(); int initValue = 3; zkMetaClient.create(key, initValue); MetaClientInterface.Stat entryStat = zkMetaClient.exists(key); Assert.assertEquals(entryStat.getVersion(), 0); // test update() and validate entry value and version Integer newData = zkMetaClient.update(key, new DataUpdater<Integer>() { @Override public Integer update(Integer currentData) { return currentData + 1; } }); Assert.assertEquals((int) newData, (int) initValue + 1); entryStat = zkMetaClient.exists(key); Assert.assertEquals(entryStat.getVersion(), 1); newData = zkMetaClient.update(key, new DataUpdater<Integer>() { @Override public Integer update(Integer currentData) { return currentData + 1; } }); entryStat = zkMetaClient.exists(key); Assert.assertEquals(entryStat.getVersion(), 2); Assert.assertEquals((int) newData, (int) initValue + 2); zkMetaClient.delete(key); } } @Test public void testGetDataAndStat() { final String key = "/TestZkMetaClient_testGetDataAndStat"; ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build(); try (ZkMetaClient<Integer> zkMetaClient = new ZkMetaClient<>(config)) { zkMetaClient.connect(); int initValue = 3; zkMetaClient.create(key, initValue); MetaClientInterface.Stat entryStat = zkMetaClient.exists(key); Assert.assertEquals(entryStat.getVersion(), 0); zkMetaClient.set(key, initValue+1, -1); ImmutablePair<Integer, MetaClientInterface.Stat> touple = zkMetaClient.getDataAndStat(key); Assert.assertEquals(touple.right.getVersion(), 1); zkMetaClient.delete(key); // test non exist key try{ zkMetaClient.getDataAndStat(key); } catch (MetaClientException ex){ Assert.assertEquals(ex.getClass().getName(), "org.apache.helix.metaclient.exception.MetaClientNoNodeException"); } } } @Test public void testGetAndCountChildrenAndRecursiveDelete() { final String key = "/TestZkMetaClient_testGetAndCountChildren"; List<String> childrenNames = Arrays.asList("/c1", "/c2", "/c3"); // create child nodes and validate retrieved children count and names try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); zkMetaClient.create(key, ENTRY_STRING_VALUE); Assert.assertEquals(zkMetaClient.countDirectChildren(key), 0); for (String str : childrenNames) { zkMetaClient.create(key + str, ENTRY_STRING_VALUE); } List<String> retrievedChildrenNames = zkMetaClient.getDirectChildrenKeys(key); Assert.assertEquals(retrievedChildrenNames.size(), childrenNames.size()); Set<String> childrenNameSet = new HashSet<>(childrenNames); for (String str : retrievedChildrenNames) { Assert.assertTrue(childrenNameSet.contains("/" + str)); } // recursive delete and validate Assert.assertEquals(zkMetaClient.countDirectChildren(key), childrenNames.size()); Assert.assertNotNull(zkMetaClient.exists(key)); zkMetaClient.recursiveDelete(key); Assert.assertNull(zkMetaClient.exists(key)); } } @Test public void testDataChangeListenerTriggerWithZkWatcher() throws Exception { final String path = "/TestZkMetaClient_testTriggerWithZkWatcher"; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); MockDataChangeListener listener = new MockDataChangeListener(); zkMetaClient.subscribeDataChange(path, listener, false); zkMetaClient.create(path, "test-node"); int expectedCallCount = 0; synchronized (_syncObject) { while (listener.getTriggeredCount() == expectedCallCount) { _syncObject.wait(DEFAULT_TIMEOUT_MS); } expectedCallCount++; Assert.assertEquals(listener.getTriggeredCount(), expectedCallCount); Assert.assertEquals(listener.getLastEventType(), DataChangeListener.ChangeType.ENTRY_CREATED); } zkMetaClient.set(path, "test-node-changed", -1); synchronized (_syncObject) { while (listener.getTriggeredCount() == expectedCallCount) { _syncObject.wait(DEFAULT_TIMEOUT_MS); } expectedCallCount++; Assert.assertEquals(listener.getTriggeredCount(), expectedCallCount); Assert.assertEquals(listener.getLastEventType(), DataChangeListener.ChangeType.ENTRY_UPDATE); } zkMetaClient.delete(path); synchronized (_syncObject) { while (listener.getTriggeredCount() == expectedCallCount) { _syncObject.wait(DEFAULT_TIMEOUT_MS); } expectedCallCount++; Assert.assertEquals(listener.getTriggeredCount(), expectedCallCount); Assert.assertEquals(listener.getLastEventType(), DataChangeListener.ChangeType.ENTRY_DELETED); } // unregister listener, expect no more call zkMetaClient.unsubscribeDataChange(path, listener); zkMetaClient.create(path, "test-node"); synchronized (_syncObject) { _syncObject.wait(DEFAULT_TIMEOUT_MS); Assert.assertEquals(listener.getTriggeredCount(), expectedCallCount); } // register a new non-persistent listener try { zkMetaClient.subscribeOneTimeDataChange(path, new MockDataChangeListener(), false); Assert.fail("One-time listener is not supported, NotImplementedException should be thrown."); } catch (NotImplementedException e) { // expected } } } @Test(dependsOnMethods = "testDataChangeListenerTriggerWithZkWatcher") public void testMultipleDataChangeListeners() throws Exception { final String basePath = "/TestZkMetaClient_testMultipleDataChangeListeners"; final int count = 5; final String testData = "test-data"; final AtomicBoolean dataExpected = new AtomicBoolean(true); try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); Map<String, Set<DataChangeListener>> listeners = new HashMap<>(); CountDownLatch countDownLatch = new CountDownLatch(count); zkMetaClient.create(basePath + "_1", testData); // create paths for (int i = 0; i < 2; i++) { String path = basePath + "_" + i; listeners.put(path, new HashSet<>()); // 5 listeners for each path for (int j = 0; j < count; j++) { DataChangeListener listener = new DataChangeListener() { @Override public void handleDataChange(String key, Object data, ChangeType changeType) { countDownLatch.countDown(); dataExpected.set(dataExpected.get() && testData.equals(data)); } }; listeners.get(path).add(listener); zkMetaClient.subscribeDataChange(path, listener, false); } } zkMetaClient.set(basePath + "_1", testData, -1); Assert.assertTrue(countDownLatch.await(DEFAULT_LISTENER_WAIT_TIMEOUT, TimeUnit.MILLISECONDS)); Assert.assertTrue(dataExpected.get()); } } @Test public void testDirectChildChangeListener() throws Exception { final String basePath = "/TestZkMetaClient_testDirectChildChangeListener"; final int count = 1000; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); CountDownLatch countDownLatch = new CountDownLatch(count); DirectChildChangeListener listener = new DirectChildChangeListener() { @Override public void handleDirectChildChange(String key) throws Exception { countDownLatch.countDown(); } }; zkMetaClient.create(basePath, ""); Assert.assertTrue( zkMetaClient.subscribeDirectChildChange(basePath, listener, false) .isRegistered()); for(int i=0; i<1000; ++i){ zkMetaClient.create(basePath + "/child_" +i, "test-data"); } // Verify no one time watcher is registered. Only one persist listener is registered. Map<String, List<String>> watchers = TestUtil.getZkWatch(zkMetaClient.getZkClient()); Assert.assertEquals(watchers.get("persistentWatches").size(), 1); Assert.assertEquals(watchers.get("persistentWatches").get(0), basePath); Assert.assertEquals(watchers.get("childWatches").size(), 0); Assert.assertEquals(watchers.get("dataWatches").size(), 0); Assert.assertTrue(countDownLatch.await(DEFAULT_LISTENER_WAIT_TIMEOUT, TimeUnit.MILLISECONDS)); zkMetaClient.unsubscribeDirectChildChange(basePath, listener); // verify that no listener is registered on any path watchers = TestUtil.getZkWatch(zkMetaClient.getZkClient()); Assert.assertEquals(watchers.get("persistentWatches").size(), 0); Assert.assertEquals(watchers.get("childWatches").size(), 0); Assert.assertEquals(watchers.get("dataWatches").size(), 0); } } @Test public void testDataChangeListener() throws Exception { final String basePath = "/TestZkMetaClient_testDataChangeListener"; final int count = 200; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); CountDownLatch countDownLatch = new CountDownLatch(count); DataChangeListener listener = new DataChangeListener() { @Override public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception { if(changeType == ENTRY_UPDATE) { countDownLatch.countDown(); } } }; zkMetaClient.create(basePath, ""); Assert.assertTrue( zkMetaClient.subscribeDataChange(basePath, listener, false) ); // Verify no one time watcher is registered. Only one persist listener is registered. Map<String, List<String>> watchers = TestUtil.getZkWatch(zkMetaClient.getZkClient()); Assert.assertEquals(watchers.get("persistentWatches").size(), 1); Assert.assertEquals(watchers.get("persistentWatches").get(0), basePath); Assert.assertEquals(watchers.get("childWatches").size(), 0); Assert.assertEquals(watchers.get("dataWatches").size(), 0); for (int i=0; i<200; ++i) { zkMetaClient.set(basePath, "data7" + i, -1); } Assert.assertTrue(countDownLatch.await(DEFAULT_LISTENER_WAIT_TIMEOUT, TimeUnit.MILLISECONDS)); zkMetaClient.unsubscribeDataChange(basePath, listener); // verify that no listener is registered on any path watchers = TestUtil.getZkWatch(zkMetaClient.getZkClient()); Assert.assertEquals(watchers.get("persistentWatches").size(), 0); Assert.assertEquals(watchers.get("childWatches").size(), 0); Assert.assertEquals(watchers.get("dataWatches").size(), 0); } } @Test public void testChildChangeListener() throws Exception { final String basePath = "/TestZkMetaClient_testChildChangeListener"; final int count = 100; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); CountDownLatch countDownLatch = new CountDownLatch(count*4); ChildChangeListener listener = new ChildChangeListener() { @Override public void handleChildChange(String changedPath, ChangeType changeType) throws Exception { countDownLatch.countDown(); } }; zkMetaClient.create(basePath, ""); Assert.assertTrue( zkMetaClient.subscribeChildChanges(basePath, listener, false) ); DataChangeListener dummyDataListener = new DataChangeListener() { @Override public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception { } }; try { zkMetaClient.subscribeDataChange(basePath, dummyDataListener, false); Assert.fail("subscribeDataChange should throw exception"); } catch (UnsupportedOperationException ex) { // we are expecting a UnsupportedOperationException, continue with test. } DirectChildChangeListener dummyCldListener = new DirectChildChangeListener() { @Override public void handleDirectChildChange(String key) throws Exception { } }; try { zkMetaClient.subscribeDirectChildChange(basePath, dummyCldListener, false); } catch ( Exception ex) { Assert.assertEquals(ex.getClass().getName(), "java.lang.UnsupportedOperationException"); } // Verify no one time watcher is registered. Only one persist listener is registered. Map<String, List<String>> watchers = TestUtil.getZkWatch(zkMetaClient.getZkClient()); Assert.assertEquals(watchers.get("persistentRecursiveWatches").size(), 1); Assert.assertEquals(watchers.get("persistentRecursiveWatches").get(0), basePath); Assert.assertEquals(watchers.get("persistentWatches").size(), 0); Assert.assertEquals(watchers.get("childWatches").size(), 0); Assert.assertEquals(watchers.get("dataWatches").size(), 0); for (int i=0; i<count; ++i) { zkMetaClient.set(basePath, "data7" + i, -1); zkMetaClient.create(basePath+"/c1_" +i , "datat"); zkMetaClient.create(basePath+"/c1_" +i + "/c2", "datat"); zkMetaClient.delete(basePath+"/c1_" +i + "/c2"); } Assert.assertTrue(countDownLatch.await(5000, TimeUnit.MILLISECONDS)); zkMetaClient.unsubscribeChildChanges(basePath, listener); // verify that no listener is registered on any path watchers = TestUtil.getZkWatch(zkMetaClient.getZkClient()); Assert.assertEquals(watchers.get("persistentRecursiveWatches").size(), 0); Assert.assertEquals(watchers.get("persistentWatches").size(), 0); Assert.assertEquals(watchers.get("childWatches").size(), 0); Assert.assertEquals(watchers.get("dataWatches").size(), 0); } } @Test public void testChangeListener() throws Exception { final String basePath = "/TestZkMetaClient_ChangeListener"; final int count = 100; try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); DataChangeListener listener = new DataChangeListener() { @Override public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception { } }; DirectChildChangeListener cldListener = new DirectChildChangeListener() { @Override public void handleDirectChildChange(String key) throws Exception { } }; zkMetaClient.subscribeDataChange(basePath, listener, true); zkMetaClient.create(basePath, ""); zkMetaClient.get(basePath); zkMetaClient.exists(basePath); zkMetaClient.getDataAndStat(basePath); zkMetaClient.getDirectChildrenKeys(basePath); zkMetaClient.subscribeDirectChildChange(basePath, cldListener, true); } } /** * Transactional op calls zk.multi() with a set of ops (operations) * and the return values are converted into metaclient opResults. * This test checks whether each op was run by verifying its opResult and * the created/deleted/set path in zk. */ @Test public void testTransactionOps() { String test_name = "/test_transaction_ops"; try(ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); //Create Nodes List<Op> ops = Arrays.asList( Op.create(TRANSACTION_TEST_PARENT_PATH, new byte[0], MetaClientInterface.EntryMode.PERSISTENT), Op.create(TRANSACTION_TEST_PARENT_PATH + test_name, new byte[0], MetaClientInterface.EntryMode.PERSISTENT), Op.delete(TRANSACTION_TEST_PARENT_PATH + test_name, -1), Op.create(TRANSACTION_TEST_PARENT_PATH + test_name, new byte[0], MetaClientInterface.EntryMode.PERSISTENT), Op.set(TRANSACTION_TEST_PARENT_PATH + test_name, new byte[0], -1)); //Execute transactional support on operations List<OpResult> opResults = zkMetaClient.transactionOP(ops); //Verify opResults types Assert.assertTrue(opResults.get(0) instanceof OpResult.CreateResult); Assert.assertTrue(opResults.get(1) instanceof OpResult.CreateResult); Assert.assertTrue(opResults.get(2) instanceof OpResult.DeleteResult); Assert.assertTrue(opResults.get(4) instanceof OpResult.SetDataResult); //Verify paths have been created MetaClientInterface.Stat entryStat = zkMetaClient.exists(TRANSACTION_TEST_PARENT_PATH + test_name); Assert.assertNotNull(entryStat, "Path should have been created."); //Cleanup zkMetaClient.recursiveDelete(TRANSACTION_TEST_PARENT_PATH); if (zkMetaClient.exists(TRANSACTION_TEST_PARENT_PATH) != null) { Assert.fail("Parent Path should have been removed."); } } } /** * This test calls transactionOp on an invalid path. * It checks that the invalid path has not been created to verify the * "all or nothing" behavior of transactionOp. * @throws KeeperException */ @Test(dependsOnMethods = "testTransactionOps") public void testTransactionFail() { String test_name = "/test_transaction_fail"; try(ZkMetaClient<String> zkMetaClient = createZkMetaClient()) { zkMetaClient.connect(); //Create Nodes List<Op> ops = Arrays.asList( Op.create(TRANSACTION_TEST_PARENT_PATH, new byte[0], MetaClientInterface.EntryMode.PERSISTENT), Op.create(TRANSACTION_TEST_PARENT_PATH + test_name, new byte[0], MetaClientInterface.EntryMode.PERSISTENT), Op.create(TEST_INVALID_PATH, new byte[0], MetaClientInterface.EntryMode.PERSISTENT)); try { zkMetaClient.transactionOP(ops); Assert.fail( "Should have thrown an exception. Cannot run transactional create OP on incorrect path."); } catch (Exception e) { MetaClientInterface.Stat entryStat = zkMetaClient.exists(TRANSACTION_TEST_PARENT_PATH); Assert.assertNull(entryStat); } } } private class MockDataChangeListener implements DataChangeListener { private final AtomicInteger _triggeredCount = new AtomicInteger(0); private volatile ChangeType _lastEventType; @Override public void handleDataChange(String key, Object data, ChangeType changeType) { _triggeredCount.getAndIncrement(); _lastEventType = changeType; synchronized (_syncObject) { _syncObject.notifyAll(); } } int getTriggeredCount() { return _triggeredCount.get(); } ChangeType getLastEventType() { return _lastEventType; } } }
9,222
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/ZkMetaClientTestBase.java
package org.apache.helix.metaclient.impl.zk; /* * 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 org.apache.commons.io.FileUtils; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.zookeeper.zkclient.IDefaultNameSpace; import org.apache.helix.zookeeper.zkclient.ZkServer; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public abstract class ZkMetaClientTestBase { protected static final String ZK_ADDR = "localhost:2183"; protected static final int DEFAULT_TIMEOUT_MS = 1000; protected static final String ENTRY_STRING_VALUE = "test-value"; private static ZkServer _zkServer; /** * Creates local Zk Server * Note: Cannot test container / TTL node end to end behavior as * the zk server setup doesn't allow for that. To enable this, zk server * setup must invoke ContainerManager.java. However, the actual * behavior has been verified to work on native ZK Client. * TODO: Modify zk server setup to include ContainerManager. * This can be done through ZooKeeperServerMain.java or * LeaderZooKeeperServer.java. */ @BeforeSuite public void prepare() { System.out.println("ZkMetaClientTestBase start "); // Enable extended types and create a ZkClient System.setProperty("zookeeper.extendedTypesEnabled", "true"); // start local zookeeper server _zkServer = startZkServer(ZK_ADDR); } @AfterSuite public void cleanUp() { System.out.println("ZkMetaClientTestBase shut down"); _zkServer.shutdown(); } protected static ZkMetaClient<String> createZkMetaClient() { ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR) //.setZkSerializer(new TestStringSerializer()) .build(); return new ZkMetaClient<>(config); } public static ZkServer startZkServer(final String zkAddress) { String zkDir = zkAddress.replace(':', '_'); final String logDir = "/tmp/" + zkDir + "/logs"; final String dataDir = "/tmp/" + zkDir + "/dataDir"; // Clean up local directory try { FileUtils.deleteDirectory(new File(dataDir)); FileUtils.deleteDirectory(new File(logDir)); } catch (IOException e) { e.printStackTrace(); } IDefaultNameSpace defaultNameSpace = zkClient -> { }; int port = Integer.parseInt(zkAddress.substring(zkAddress.lastIndexOf(':') + 1)); System.out.println("Starting ZK server at " + zkAddress); ZkServer zkServer = new ZkServer(dataDir, logDir, defaultNameSpace, port); zkServer.start(); return zkServer; } }
9,223
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java
package org.apache.helix.metaclient.impl.zk; /* * 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.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.helix.zookeeper.api.client.HelixZkClient; import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; 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.ZooKeeper; import org.testng.Assert; public class TestUtil { public static final long AUTO_RECONNECT_TIMEOUT_MS_FOR_TEST = 3 * 1000; public static final long AUTO_RECONNECT_WAIT_TIME_WITHIN = 1 * 1000; public static final long AUTO_RECONNECT_WAIT_TIME_EXD = 5 * 1000; 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; } 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); field2 = getField(watchManager.getClass(), "persistentWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> persistentWatches = (HashMap<String, Set<Watcher>>) field2.get(watchManager); field2 = getField(watchManager.getClass(), "persistentRecursiveWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> persistentRecursiveWatches = (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())); lists.put("persistentWatches", new ArrayList<>(persistentWatches.keySet())); lists.put("persistentRecursiveWatches", new ArrayList<>(persistentRecursiveWatches.keySet())); return lists; } public static void expireSession(ZkMetaClient client) throws Exception { final CountDownLatch waitNewSession = new CountDownLatch(1); final ZkClient zkClient = client.getZkClient(); IZkStateListener listener = new IZkStateListener() { @Override public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception { } @Override public void handleNewSession(final String sessionId) throws Exception { // make sure zkclient is connected again zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS); 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()); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { } }; final ZooKeeper dupZookeeper = new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher, curZookeeper.getSessionId(), curZookeeper.getSessionPasswd()); // wait until connected, then close while (dupZookeeper.getState() != ZooKeeper.States.CONNECTED) { Thread.sleep(10); } Assert.assertEquals(dupZookeeper.getState(), ZooKeeper.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()); Assert.assertFalse(newSessionId.equals(oldSessionId), "Fail to expire current session, zk: " + curZookeeper); } /** * Simulate a zk state change by calling {@link ZkClient#process(WatchedEvent)} directly * This need to be done in a separate thread to simulate ZkClient eventThread. */ public static void simulateZkStateReconnected(ZkMetaClient client) throws InterruptedException { final ZkClient zkClient = client.getZkClient(); WatchedEvent event = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null); zkClient.process(event); Thread.sleep(AUTO_RECONNECT_WAIT_TIME_WITHIN); event = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.SyncConnected, null); zkClient.process(event); } }
9,224
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java
package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest; /* * 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.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.exception.MetaClientNodeExistsException; import org.apache.helix.metaclient.puppy.AbstractPuppy; import org.apache.helix.metaclient.puppy.PuppySpec; import java.util.Random; public class CreatePuppy extends AbstractPuppy { private final Random _random; private final String _parentPath = "/test"; public CreatePuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) { super(metaclient, puppySpec); _random = new Random(); } @Override protected void bark() { // Implement the chaos logic for creating nodes int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths()); if (shouldIntroduceError()) { try { // Simulate an error by creating an invalid path _metaclient.create("invalid", "test"); } catch (IllegalArgumentException e) { // Catch invalid exception System.out.println(Thread.currentThread().getName() + " tried to create an invalid path" + " at time: " + System.currentTimeMillis()); // Expected exception } } else { // Normal behavior - create a new node try { System.out.println(Thread.currentThread().getName() + " is attempting to create node: " + randomNumber + " at time: " + System.currentTimeMillis()); _metaclient.create(_parentPath + "/" + randomNumber,"test"); System.out.println(Thread.currentThread().getName() + " successfully created node " + randomNumber + " at time: " + System.currentTimeMillis()); _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1); } catch (MetaClientNodeExistsException e) { // Expected exception System.out.println(Thread.currentThread().getName() + " failed to create node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it already exists"); } } } @Override protected void cleanup() { // Cleanup logic in test case } private boolean shouldIntroduceError() { float randomValue = _random.nextFloat(); return randomValue < _puppySpec.getErrorRate(); } }
9,225
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java
package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest; /* * 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.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.puppy.AbstractPuppy; import org.apache.helix.metaclient.puppy.PuppySpec; import java.util.Objects; import java.util.Random; public class GetPuppy extends AbstractPuppy { private final Random _random; private final String _parentPath = "/test"; public GetPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) { super(metaclient, puppySpec); _random = new Random(); } @Override protected void bark() { int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths()); if (shouldIntroduceError()) { try { _metaclient.get("invalid"); _unhandledErrorCounter++; } catch (IllegalArgumentException e) { System.out.println(Thread.currentThread().getName() + " intentionally tried to read an invalid path" + " at time: " + System.currentTimeMillis()); } } else { System.out.println(Thread.currentThread().getName() + " is attempting to read node: " + randomNumber + " at time: " + System.currentTimeMillis()); String nodeValue = _metaclient.get(_parentPath + "/" + randomNumber); if (Objects.equals(nodeValue, null)) { System.out.println(Thread.currentThread().getName() + " failed to read node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist"); } else { System.out.println(Thread.currentThread().getName() + " successfully read node " + randomNumber + " at time: " + System.currentTimeMillis()); } } } @Override protected void cleanup() { } private boolean shouldIntroduceError() { return _random.nextFloat() < _puppySpec.getErrorRate(); } }
9,226
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java
package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest; /* * 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.metaclient.api.ChildChangeListener; import org.apache.helix.metaclient.impl.zk.ZkMetaClient; import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase; import org.apache.helix.metaclient.puppy.ExecDelay; import org.apache.helix.metaclient.puppy.PuppyManager; import org.apache.helix.metaclient.puppy.PuppyMode; import org.apache.helix.metaclient.puppy.PuppySpec; import org.apache.helix.metaclient.puppy.AbstractPuppy; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class TestMultiThreadStressZKClient extends ZkMetaClientTestBase { private ZkMetaClient<String> _zkMetaClient; private final String zkParentKey = "/test"; private final long TIMEOUT = 60; // The desired timeout duration of tests in seconds @BeforeTest private void setUp() { this._zkMetaClient = createZkMetaClient(); this._zkMetaClient.connect(); } @Test public void testCreatePuppy() { _zkMetaClient.create(zkParentKey, "test"); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); CreatePuppy createPuppy2 = new CreatePuppy(_zkMetaClient, puppySpec); CreatePuppy createPuppy3 = new CreatePuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(createPuppy2); puppyManager.addPuppy(createPuppy3); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, null); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testDeletePuppy() { _zkMetaClient.create(zkParentKey, "test"); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(deletePuppy); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, null); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testGetPuppy() { _zkMetaClient.create(zkParentKey, "test"); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(getPuppy); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, null); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testSetPuppy() { _zkMetaClient.create(zkParentKey, "test"); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(setPuppy); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, null); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testUpdatePuppy() { _zkMetaClient.create(zkParentKey, "test"); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(updatePuppy); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, null); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testCrudPuppies() { _zkMetaClient.create(zkParentKey, "test"); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec); DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec); SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec); UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(getPuppy); puppyManager.addPuppy(deletePuppy); puppyManager.addPuppy(setPuppy); puppyManager.addPuppy(updatePuppy); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, null); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testBasicParentListenerPuppy() { _zkMetaClient.create(zkParentKey, "test"); AtomicInteger globalChildChangeCounter = new AtomicInteger(); ChildChangeListener childChangeListener = (changedPath, changeType) -> { globalChildChangeCounter.addAndGet(1); System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + ". Number of total changes: " + globalChildChangeCounter.get()); }; _zkMetaClient.subscribeChildChanges(zkParentKey, childChangeListener, false); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, globalChildChangeCounter); // cleanup _zkMetaClient.unsubscribeChildChanges(zkParentKey, childChangeListener); _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } @Test public void testComplexParentListenerPuppy() { _zkMetaClient.create(zkParentKey, "test"); // Global counter for all child changes AtomicInteger globalChildChangeCounter = new AtomicInteger(); ChildChangeListener childChangeListener = (changedPath, changeType) -> { globalChildChangeCounter.addAndGet(1); System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + globalChildChangeCounter.get()); }; _zkMetaClient.subscribeChildChanges(zkParentKey, childChangeListener, false); PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec); DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec); SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec); UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(getPuppy); puppyManager.addPuppy(deletePuppy); puppyManager.addPuppy(setPuppy); puppyManager.addPuppy(updatePuppy); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, globalChildChangeCounter); // cleanup _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); _zkMetaClient.unsubscribeChildChanges(zkParentKey, childChangeListener); _zkMetaClient.delete(zkParentKey); } @Test public void testChildListenerPuppy() { _zkMetaClient.create(zkParentKey, "test"); // Setting num diff paths to 3 until we find a better way of scaling listeners. PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 3); CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec); GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec); DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec); SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec); UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(createPuppy); puppyManager.addPuppy(getPuppy); puppyManager.addPuppy(deletePuppy); puppyManager.addPuppy(setPuppy); puppyManager.addPuppy(updatePuppy); // Create a child listener for each child defined in number diff paths in puppyspec. // TODO: Make this a parameter for a loop. AtomicInteger childChangeCounter0 = new AtomicInteger(); ChildChangeListener childChangeListener0 = (changedPath, changeType) -> { childChangeCounter0.addAndGet(1); System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + childChangeCounter0.get()); }; _zkMetaClient.subscribeChildChanges("/test/0", childChangeListener0, false); AtomicInteger childChangeCounter1 = new AtomicInteger(); ChildChangeListener childChangeListener1 = (changedPath, changeType) -> { childChangeCounter1.addAndGet(1); System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + childChangeCounter1.get()); }; _zkMetaClient.subscribeChildChanges("/test/1", childChangeListener1, false); AtomicInteger childChangeCounter2 = new AtomicInteger(); ChildChangeListener childChangeListener2 = (changedPath, changeType) -> { childChangeCounter2.addAndGet(1); System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + childChangeCounter2.get()); }; _zkMetaClient.subscribeChildChanges("/test/2", childChangeListener2, false); puppyManager.start(TIMEOUT); assertNoExceptions(puppyManager, null); // Add all event changes from all puppies and compare with child change listener // Inner merged by path Map<String, Integer> mergedEventChangeCounterMap = new HashMap<>(); for (AbstractPuppy puppy : puppyManager.getPuppies()) { puppy._eventChangeCounterMap.forEach((key, value) -> { if (mergedEventChangeCounterMap.containsKey(key)) { mergedEventChangeCounterMap.put(key, mergedEventChangeCounterMap.get(key) + value); } else { mergedEventChangeCounterMap.put(key, value); } }); } System.out.println("Merged event change counter map: " + mergedEventChangeCounterMap); System.out.println("Child change counter 0: " + childChangeCounter0); System.out.println("Child change counter 1: " + childChangeCounter1); System.out.println("Child change counter 2: " + childChangeCounter2); Assert.assertEquals(childChangeCounter0.get(), mergedEventChangeCounterMap.getOrDefault("0", 0).intValue()); Assert.assertEquals(childChangeCounter1.get(), mergedEventChangeCounterMap.getOrDefault("1", 0).intValue()); Assert.assertEquals(childChangeCounter2.get(), mergedEventChangeCounterMap.getOrDefault("2", 0).intValue()); // cleanup _zkMetaClient.unsubscribeChildChanges("/test/0", childChangeListener0); _zkMetaClient.unsubscribeChildChanges("/test/1", childChangeListener1); _zkMetaClient.unsubscribeChildChanges("/test/2", childChangeListener2); _zkMetaClient.recursiveDelete(zkParentKey); Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0); } private void assertNoExceptions(PuppyManager puppyManager, AtomicInteger globalChangeCounter) { int totalUnhandledErrors = 0; int totalEventChanges = 0; // Add all change counters and compare with event change listener for (AbstractPuppy puppy : puppyManager.getPuppies()) { AtomicInteger totalHandledErrors = new AtomicInteger(); puppy._eventChangeCounterMap.forEach((key, value) -> { totalHandledErrors.addAndGet(value); }); System.out.println("Change counter: " + totalHandledErrors + " for " + puppy.getClass()); System.out.println("Error counter: " + puppy._unhandledErrorCounter + " for " + puppy.getClass()); totalUnhandledErrors += puppy._unhandledErrorCounter; totalEventChanges += totalHandledErrors.get(); } // Assert no unhandled (unexpected) exceptions and that the child change listener placed on // test parent node (/test) caught all successful changes that were recorded by each puppy Assert.assertEquals(totalUnhandledErrors, 0); // Assert that the global change counter matches the total number of events recorded by each puppy if (globalChangeCounter != null) { Assert.assertEquals(totalEventChanges, globalChangeCounter.get()); } } }
9,227
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java
package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest; /* * 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.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.exception.MetaClientNoNodeException; import org.apache.helix.metaclient.puppy.AbstractPuppy; import org.apache.helix.metaclient.puppy.PuppySpec; import java.util.Random; public class UpdatePuppy extends AbstractPuppy { private final Random _random; private final String _parentPath = "/test"; public UpdatePuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) { super(metaclient, puppySpec); _random = new Random(); } @Override protected void bark() throws Exception { int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths()); if (shouldIntroduceError()) { try { _metaclient.update("invalid", (data) -> "foo"); } catch (IllegalArgumentException e) { System.out.println(Thread.currentThread().getName() + " intentionally tried to update an invalid path" + " at time: " + System.currentTimeMillis()); } } else { try { System.out.println(Thread.currentThread().getName() + " is attempting to update node: " + randomNumber + " at time: " + System.currentTimeMillis()); _metaclient.update(_parentPath + "/" + randomNumber, (data) -> "foo"); _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1); System.out.println(Thread.currentThread().getName() + " successfully updated node " + randomNumber + " at time: " + System.currentTimeMillis()); } catch (MetaClientNoNodeException e) { System.out.println(Thread.currentThread().getName() + " failed to update node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist"); } catch (IllegalArgumentException e) { if (!e.getMessage().equals("Can not subscribe one time watcher when ZkClient is using PersistWatcher")) { throw e; } } } } @Override protected void cleanup() { } private boolean shouldIntroduceError() { float randomValue = _random.nextFloat(); return randomValue < _puppySpec.getErrorRate(); } }
9,228
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java
package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest; /* * 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.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.puppy.AbstractPuppy; import org.apache.helix.metaclient.puppy.PuppySpec; import java.util.Random; public class DeletePuppy extends AbstractPuppy { private final Random _random; private final String _parentPath = "/test"; public DeletePuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) { super(metaclient, puppySpec); _random = new Random(); } @Override protected void bark() { int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths()); if (shouldIntroduceError()) { try { _metaclient.delete("invalid"); _unhandledErrorCounter++; } catch (IllegalArgumentException e) { System.out.println(Thread.currentThread().getName() + " intentionally deleted an invalid path" + " at time: " + System.currentTimeMillis() ); } } else { System.out.println(Thread.currentThread().getName() + " is attempting to delete node: " + randomNumber + " at time: " + System.currentTimeMillis()); if (_metaclient.delete(_parentPath + "/" + randomNumber)) { System.out.println(Thread.currentThread().getName() + " successfully deleted node " + randomNumber + " at time: " + System.currentTimeMillis()); _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1); } else { System.out.println(Thread.currentThread().getName() + " failed to delete node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist"); } } } @Override protected void cleanup() { // Do nothing } private boolean shouldIntroduceError() { return _random.nextFloat() < _puppySpec.getErrorRate(); } }
9,229
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java
package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest; /* * 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.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.exception.MetaClientNoNodeException; import org.apache.helix.metaclient.puppy.AbstractPuppy; import org.apache.helix.metaclient.puppy.PuppySpec; import java.util.Random; public class SetPuppy extends AbstractPuppy { private final Random _random; private final String _parentPath = "/test"; public SetPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) { super(metaclient, puppySpec); _random = new Random(); } @Override protected void bark() { int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths()); if (shouldIntroduceError()) { try { _metaclient.set("invalid", "test", -1); } catch (IllegalArgumentException e) { System.out.println(Thread.currentThread().getName() + " intentionally called set on an invalid path" + " at time: " + System.currentTimeMillis()); } } else { try { System.out.println(Thread.currentThread().getName() + " is attempting to set node: " + randomNumber + " at time: " + System.currentTimeMillis()); _metaclient.set(_parentPath + "/" + randomNumber, "test", -1); _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1); System.out.println( Thread.currentThread().getName() + " successfully set node " + randomNumber + " at time: " + System.currentTimeMillis()); } catch (MetaClientNoNodeException e) { System.out.println(Thread.currentThread().getName() + " failed to set node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist"); } } } @Override protected void cleanup() { } private boolean shouldIntroduceError() { float randomValue = _random.nextFloat(); return randomValue < _puppySpec.getErrorRate(); } }
9,230
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyMode.java
package org.apache.helix.metaclient.puppy; /* * 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. */ /** * Enum for Puppy mode (OneOff or Repeat) */ public enum PuppyMode { ONE_OFF, REPEAT }
9,231
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppySpec.java
package org.apache.helix.metaclient.puppy; /* * 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. */ /** * PuppySpec class definition */ public class PuppySpec { private final PuppyMode _mode; private final float _errorRate; private final ExecDelay _execDelay; private final int _numberDiffPaths; public PuppySpec(PuppyMode mode, float errorRate, ExecDelay execDelay, int numberDiffPaths) { _mode = mode; _errorRate = errorRate; _execDelay = execDelay; _numberDiffPaths = numberDiffPaths; } public PuppyMode getMode() { return _mode; } public float getErrorRate() { return _errorRate; } public ExecDelay getExecDelay() { return _execDelay; } public int getNumberDiffPaths() { return _numberDiffPaths; } }
9,232
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyManager.java
package org.apache.helix.metaclient.puppy; /* * 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.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * This class is used to manage the lifecycle of a set of _puppies. */ public class PuppyManager { private final List<AbstractPuppy> _puppies = new ArrayList<>(); private final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool(); public PuppyManager() { } public void addPuppy(AbstractPuppy puppy) { _puppies.add(puppy); } public List<AbstractPuppy> getPuppies() { return _puppies; } public void start(long timeoutInSeconds) { for (AbstractPuppy puppy : _puppies) { EXECUTOR_SERVICE.submit(puppy); } try { EXECUTOR_SERVICE.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS); } catch (InterruptedException e) { // Ignore } stop(); } public void stop() { EXECUTOR_SERVICE.shutdownNow(); } }
9,233
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
package org.apache.helix.metaclient.puppy; /* * 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.metaclient.api.MetaClientInterface; import java.util.HashMap; /** * AbstractPuppy object contains interfaces to implement puppy and main logics to manage puppy life cycle */ public abstract class AbstractPuppy implements Runnable { protected MetaClientInterface<String> _metaclient; protected PuppySpec _puppySpec; public final HashMap<String, Integer> _eventChangeCounterMap; public int _unhandledErrorCounter; public AbstractPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) { _metaclient = metaclient; _puppySpec = puppySpec; _eventChangeCounterMap = new HashMap<>(); } /** * Implements puppy's main logic. Puppy needs to implement its chaos logic, recovery logic based on * errorRate, recoverDelay. For OneOff puppy, it will bark once with execDelay in spec, and for * Repeat puppy, it will bark forever, with execDelay between 2 barks */ protected abstract void bark() throws Exception; /** * Implements puppy's final cleanup logic - it will be called only once right before the puppy terminates. * Before the puppy terminates, it needs to recover from all chaos it created. */ protected abstract void cleanup(); @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(getPuppySpec().getExecDelay().getNextDelay()); bark(); } catch (InterruptedException e) { break; } catch (Exception e) { incrementUnhandledErrorCounter(); e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } finally { cleanup(); } } public PuppySpec getPuppySpec() { return _puppySpec; } public int getUnhandledErrorCounter() { return _unhandledErrorCounter; } private void incrementUnhandledErrorCounter() { _unhandledErrorCounter++; } }
9,234
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/puppy/ExecDelay.java
package org.apache.helix.metaclient.puppy; /* * 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.Random; /** * ExecDelay class definition */ public class ExecDelay { private final long _duration; private final float _jitter; private final long _delayBase; private final long _delayRange; private final Random _random; public ExecDelay(long duration, float jitter) { if (jitter < 0 || jitter > 1 || duration < 0) { throw new IllegalArgumentException( String.format("Invalid _jitter (%s) or _duration (%s)", jitter, duration)); } _duration = duration; _jitter = jitter; _delayRange = Math.round(_duration * _jitter * 2); _delayBase = _duration - _delayRange / 2; _random = new Random(); } /** * Calculate the next delay based on the configured _duration and _jitter. * @return The next delay in milliseconds. */ public long getNextDelay() { long randomDelay = _delayBase + _random.nextLong() % _delayRange; return Math.max(randomDelay, 0); } public long getDuration() { return _duration; } public float getJitter() { return _jitter; } }
9,235
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphoreTest.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collection; public class DistributedSemaphoreTest extends ZkMetaClientTestBase { public DistributedSemaphore createSemaphoreClientAndSemaphore(String path, int capacity) { MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER; MetaClientConfig config = new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR) .setStoreType(storeType).build(); DistributedSemaphore client = new DistributedSemaphore(config); client.createSemaphore(path, capacity); return client; } @Test public void testAcquirePermit() { final String key = "/TestSemaphore_testAcquirePermit"; int capacity = 5; DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity); Permit permit = semaphoreClient.acquire(); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 1); } @Test public void testAcquireMultiplePermits() { final String key = "/TestSemaphore_testAcquireMultiplePermits"; int capacity = 5; int count = 4; DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity); Collection<Permit> permits = semaphoreClient.acquire(count); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 4); Assert.assertEquals(permits.size(), count); Assert.assertNull(semaphoreClient.acquire(count)); } @Test public void testReturnPermit() { final String key = "/TestSemaphore_testReturnPermit"; int capacity = 5; DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity); Permit permit = semaphoreClient.acquire(); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 1); semaphoreClient.returnPermit(permit); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity); // return the same permit again. Should not fail but capacity remains same. semaphoreClient.returnPermit(permit); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity); } @Test public void testReturnMultiplePermits() { final String key = "/TestSemaphore_testReturnMultiplePermits"; int capacity = 5; int count = 4; DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity); Collection<Permit> permits = semaphoreClient.acquire(count); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 4); Assert.assertEquals(permits.size(), count); semaphoreClient.returnAllPermits(permits); Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity); } @Test public void testTryAcquirePermit() { // Not implemented } }
9,236
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/LockInfoTest.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.time.Duration; import org.apache.helix.metaclient.datamodel.DataRecord; import org.testng.Assert; import org.testng.annotations.Test; public class LockInfoTest { private static final String OWNER_ID = "urn:li:principal:UNKNOWN"; private static final String CLIENT_ID = "test_client_id"; private static final String CLIENT_DATA = "client_data"; private static final String LOCK_ID = "794c8a4c-c14b-4c23-b83f-4e1147fc6978"; private static final long GRANT_TIME = System.currentTimeMillis(); private static final long LAST_RENEWAL_TIME = System.currentTimeMillis(); private static final long TIMEOUT = 100000; public static final String DEFAULT_LOCK_ID_TEXT = ""; public static final String DEFAULT_OWNER_ID_TEXT = ""; public static final String DEFAULT_CLIENT_ID_TEXT = ""; public static final String DEFAULT_CLIENT_DATA = ""; public static final long DEFAULT_GRANTED_AT_LONG = -1L; public static final long DEFAULT_LAST_RENEWED_AT_LONG = -1L; public static final long DEFAULT_TIMEOUT_DURATION = -1L; @Test public void testLockInfo() { LockInfo lockInfo = new LockInfo(LOCK_ID, OWNER_ID, CLIENT_ID, CLIENT_DATA, GRANT_TIME, LAST_RENEWAL_TIME, TIMEOUT); Assert.assertEquals(LOCK_ID, lockInfo.getLockId()); Assert.assertEquals(OWNER_ID, lockInfo.getOwnerId()); Assert.assertEquals(CLIENT_ID, lockInfo.getClientId()); Assert.assertEquals(CLIENT_DATA, lockInfo.getClientData()); Assert.assertEquals(GRANT_TIME, (long) lockInfo.getGrantedAt()); Assert.assertEquals(LAST_RENEWAL_TIME, (long) lockInfo.getLastRenewedAt()); Assert.assertEquals(TIMEOUT, lockInfo.getTimeout()); DataRecord dataRecord = new DataRecord("dataRecord"); LockInfo lockInfo1 = new LockInfo(dataRecord); Assert.assertEquals(DEFAULT_LOCK_ID_TEXT, lockInfo1.getLockId()); Assert.assertEquals(DEFAULT_OWNER_ID_TEXT, lockInfo1.getOwnerId()); Assert.assertEquals(DEFAULT_CLIENT_ID_TEXT, lockInfo1.getClientId()); Assert.assertEquals(DEFAULT_CLIENT_DATA, lockInfo1.getClientData()); Assert.assertEquals(DEFAULT_GRANTED_AT_LONG, (long) lockInfo1.getGrantedAt()); Assert.assertEquals(DEFAULT_LAST_RENEWED_AT_LONG, (long) lockInfo1.getLastRenewedAt()); Assert.assertEquals(DEFAULT_TIMEOUT_DURATION, lockInfo1.getTimeout()); } }
9,237
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/LockClientTest.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase; import org.testng.Assert; import org.testng.annotations.Test; public class LockClientTest extends ZkMetaClientTestBase { private static final String TEST_INVALID_PATH = "/_invalid/a/b/c"; private static final String OWNER_ID = "urn:li:principal:UNKNOWN"; private static final String CLIENT_ID = "test_client_id"; private static final String CLIENT_DATA = "client_data"; private static final String LOCK_ID = "794c8a4c-c14b-4c23-b83f-4e1147fc6978"; private static final long GRANT_TIME = System.currentTimeMillis(); private static final long LAST_RENEWAL_TIME = System.currentTimeMillis(); private static final long TIMEOUT = 100000; public LockClient createLockClient() { MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER; MetaClientConfig config = new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR) .setStoreType(storeType).build(); return new LockClient(config); } private LockInfo createLockInfo() { LockInfo lockInfo = new LockInfo(); lockInfo.setOwnerId(OWNER_ID); lockInfo.setClientId(CLIENT_ID); lockInfo.setClientData(CLIENT_DATA); lockInfo.setLockId(LOCK_ID); lockInfo.setGrantedAt(GRANT_TIME); lockInfo.setLastRenewedAt(LAST_RENEWAL_TIME); lockInfo.setTimeout(TIMEOUT); return lockInfo; } @Test public void testAcquireLock() { final String key = "/TestLockClient_testAcquireLock"; LockClient lockClient = createLockClient(); LockInfo lockInfo = createLockInfo(); lockClient.acquireLock(key, lockInfo, MetaClientInterface.EntryMode.PERSISTENT); Assert.assertNotNull(lockClient.retrieveLock(key)); try { lockClient.acquireLock(TEST_INVALID_PATH, new LockInfo(), MetaClientInterface.EntryMode.PERSISTENT); Assert.fail("Should not be able to acquire lock for key: " + key); } catch (Exception e) { // expected } } @Test public void testReleaseLock() { final String key = "/TestLockClient_testReleaseLock"; LockClient lockClient = createLockClient(); LockInfo lockInfo = createLockInfo(); lockClient.acquireLock(key, lockInfo, MetaClientInterface.EntryMode.PERSISTENT); Assert.assertNotNull(lockClient.retrieveLock(key)); lockClient.releaseLock(key); Assert.assertNull(lockClient.retrieveLock(key)); lockClient.releaseLock(TEST_INVALID_PATH); } @Test public void testAcquireTTLLock() { final String key = "/TestLockClient_testAcquireTTLLock"; LockClient lockClient = createLockClient(); LockInfo lockInfo = createLockInfo(); lockClient.acquireLockWithTTL(key, lockInfo, 1L); Assert.assertNotNull(lockClient.retrieveLock(key)); try { lockClient.acquireLockWithTTL(TEST_INVALID_PATH, lockInfo, 1L); Assert.fail("Should not be able to acquire lock for key: " + key); } catch (Exception e) { // expected } } @Test public void testRetrieveLock() { final String key = "/TestLockClient_testRetrieveLock"; LockClient lockClient = createLockClient(); LockInfo lockInfo = createLockInfo(); lockClient.acquireLock(key, lockInfo, MetaClientInterface.EntryMode.PERSISTENT); Assert.assertNotNull(lockClient.retrieveLock(key)); Assert.assertEquals(lockClient.retrieveLock(key).getOwnerId(), OWNER_ID); Assert.assertEquals(lockClient.retrieveLock(key).getClientId(), CLIENT_ID); Assert.assertEquals(lockClient.retrieveLock(key).getClientData(), CLIENT_DATA); Assert.assertEquals(lockClient.retrieveLock(key).getLockId(), LOCK_ID); Assert.assertEquals(lockClient.retrieveLock(key).getTimeout(), TIMEOUT); Assert.assertNull(lockClient.retrieveLock(TEST_INVALID_PATH)); } @Test public void testRenewTTLLock() { final String key = "/TestLockClient_testRenewTTLLock"; LockClient lockClient = createLockClient(); LockInfo lockInfo = createLockInfo(); lockClient.acquireLockWithTTL(key, lockInfo, 1L); Assert.assertNotNull(lockClient.retrieveLock(key)); lockClient.renewTTLLock(key); Assert.assertNotSame(lockClient.retrieveLock(key).getGrantedAt(), lockClient.retrieveLock(key).getLastRenewedAt()); try { lockClient.renewTTLLock(TEST_INVALID_PATH); Assert.fail("Should not be able to renew lock for key: " + key); } catch (Exception e) { // expected } } }
9,238
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java
package org.apache.helix.metaclient.recipes.leaderelection; /* * 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.Random; import java.util.concurrent.TimeUnit; import org.apache.helix.metaclient.MetaClientTestUtil; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.puppy.AbstractPuppy; import org.apache.helix.metaclient.puppy.PuppySpec; import org.testng.Assert; public class LeaderElectionPuppy extends AbstractPuppy { String _leaderGroup; String _participant; private final Random _random; LeaderElectionClient _leaderElectionClient; public LeaderElectionPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) { super(metaclient, puppySpec); _random = new Random(); } public LeaderElectionPuppy(LeaderElectionClient leaderElectionClient, PuppySpec puppySpec, String leaderGroup, String participant) { super(leaderElectionClient.getMetaClient(), puppySpec); _leaderElectionClient = leaderElectionClient; _leaderGroup = leaderGroup; _random = new Random(); _participant = participant; } @Override protected void bark() throws Exception { int randomNumber = _random.nextInt((int) TimeUnit.SECONDS.toMillis(5)); System.out.println("LeaderElectionPuppy " + _participant + " Joining"); _leaderElectionClient.joinLeaderElectionParticipantPool(_leaderGroup); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (_leaderElectionClient.getLeader(_leaderGroup) != null); }, MetaClientTestUtil.WAIT_DURATION)); if (_random.nextBoolean()) { _leaderElectionClient.relinquishLeader(_leaderGroup); } Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (_leaderElectionClient.getParticipantInfo(_leaderGroup, _participant) != null); }, MetaClientTestUtil.WAIT_DURATION)); Thread.sleep(randomNumber); System.out.println("LeaderElectionPuppy " + _participant + " Leaving"); _leaderElectionClient.exitLeaderElectionParticipantPool(_leaderGroup); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (_leaderElectionClient.getParticipantInfo(_leaderGroup, _participant) == null); }, MetaClientTestUtil.WAIT_DURATION)); Thread.sleep(randomNumber); } @Override protected void cleanup() { try { System.out.println("Cleaning - LeaderElectionPuppy " + _participant + " Leaving"); _leaderElectionClient.exitLeaderElectionParticipantPool(_leaderGroup); } catch (MetaClientException ignore) { // already leave the pool. OK to throw exception. } finally { try { _leaderElectionClient.close(); } catch (Exception e) { } } } }
9,239
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java
package org.apache.helix.metaclient.recipes.leaderelection; /* * 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.metaclient.MetaClientTestUtil; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest.CreatePuppy; import org.apache.helix.metaclient.impl.zk.ZkMetaClient; import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase; import org.apache.helix.metaclient.puppy.ExecDelay; import org.apache.helix.metaclient.puppy.PuppyManager; import org.apache.helix.metaclient.puppy.PuppyMode; import org.apache.helix.metaclient.puppy.PuppySpec; import org.apache.helix.zookeeper.exception.ZkClientException; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase.*; public class TestMultiClientLeaderElection extends ZkMetaClientTestBase { private final String _leaderElectionGroup = "/Parent/a/LEADER_ELECTION_GROUP"; private ZkMetaClient<String> _zkMetaClient; private final String _participant1 = "participant_1"; private final String _participant2 = "participant_2"; @BeforeTest private void setUp() { System.out.println("STARTING TestMultiClientLeaderElection"); this._zkMetaClient = createZkMetaClient(); this._zkMetaClient.connect(); _zkMetaClient.create("/Parent", ""); _zkMetaClient.create("/Parent/a", ""); } @AfterTest @Override public void cleanUp() { try { _zkMetaClient.recursiveDelete(_leaderElectionGroup); } catch (MetaClientException ex) { _zkMetaClient.recursiveDelete(_leaderElectionGroup); } finally { _zkMetaClient.close(); } } @Test public void testLeaderElectionPuppy() { System.out.println("Starting TestMultiClientLeaderElection.testLeaderElectionPuppy"); PuppySpec puppySpec = new org.apache.helix.metaclient.puppy.PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5); LeaderElectionPuppy leaderElectionPuppy1 = new LeaderElectionPuppy(TestLeaderElection.createLeaderElectionClient(_participant1), puppySpec, _leaderElectionGroup, _participant1); LeaderElectionPuppy leaderElectionPuppy2 = new LeaderElectionPuppy(TestLeaderElection.createLeaderElectionClient(_participant2), puppySpec, _leaderElectionGroup, _participant2); PuppyManager puppyManager = new PuppyManager(); puppyManager.addPuppy(leaderElectionPuppy1); puppyManager.addPuppy(leaderElectionPuppy2); puppyManager.start(60); System.out.println("Ending TestMultiClientLeaderElection.testLeaderElectionPuppy"); } }
9,240
0
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
package org.apache.helix.metaclient.recipes.leaderelection; import java.util.ConcurrentModificationException; import org.apache.helix.metaclient.MetaClientTestUtil; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.helix.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.impl.zk.TestUtil; import org.apache.helix.metaclient.impl.zk.ZkMetaClient; import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; import static org.apache.helix.metaclient.impl.zk.TestUtil.*; public class TestLeaderElection extends ZkMetaClientTestBase { private static final String PARTICIPANT_NAME1 = "participant_1"; private static final String PARTICIPANT_NAME2 = "participant_2"; private static final String LEADER_PATH = "/LEADER_ELECTION_GROUP_1"; public static LeaderElectionClient createLeaderElectionClient(String participantName) { MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER; MetaClientConfig config = new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR).setStoreType(storeType).build(); return new LeaderElectionClient(config, participantName); } @AfterTest @Override public void cleanUp() { ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR) .build(); try (ZkMetaClient<ZNRecord> client = new ZkMetaClient<>(config)) { client.connect(); client.recursiveDelete(LEADER_PATH); } } @Test public void testAcquireLeadership() throws Exception { System.out.println("START TestLeaderElection.testAcquireLeadership"); String leaderPath = LEADER_PATH + "/testAcquireLeadership"; // create 2 clients representing 2 participants LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1); LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2); clt1.getMetaClient().create(LEADER_PATH, new LeaderInfo(LEADER_PATH)); clt1.joinLeaderElectionParticipantPool(leaderPath); clt2.joinLeaderElectionParticipantPool(leaderPath); // First client joining the leader election group should be current leader Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertNotNull(clt1.getLeader(leaderPath)); Assert.assertEquals(clt1.getLeader(leaderPath), clt2.getLeader(leaderPath)); Assert.assertEquals(clt1.getLeader(leaderPath), PARTICIPANT_NAME1); // client 1 exit leader election group, and client 2 should be current leader. clt1.exitLeaderElectionParticipantPool(leaderPath); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME2)); }, MetaClientTestUtil.WAIT_DURATION)); // client1 join and client2 leave. client 1 should be leader. clt1.joinLeaderElectionParticipantPool(leaderPath); clt2.exitLeaderElectionParticipantPool(leaderPath); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME1)); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(clt1.isLeader(leaderPath)); Assert.assertFalse(clt2.isLeader(leaderPath)); clt1.close(); clt2.close(); System.out.println("END TestLeaderElection.testAcquireLeadership"); } @Test(dependsOnMethods = "testAcquireLeadership") public void testElectionPoolMembership() throws Exception { System.out.println("START TestLeaderElection.testElectionPoolMembership"); String leaderPath = LEADER_PATH + "/_testElectionPoolMembership"; LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1); participantInfo.setSimpleField("Key1", "value1"); LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2); participantInfo2.setSimpleField("Key2", "value2"); LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1); LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2); clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); try { clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); // no op } catch (ConcurrentModificationException ex) { // expected Assert.assertEquals(ex.getClass().getName(), "java.util.ConcurrentModificationException"); } clt2.joinLeaderElectionParticipantPool(leaderPath, participantInfo2); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertNotNull(clt1.getLeaderEntryStat(leaderPath)); Assert.assertNotNull(clt1.getLeader(leaderPath)); Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1"); Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1"); Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2"); Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2"); // clt1 gone clt1.relinquishLeader(leaderPath); clt1.exitLeaderElectionParticipantPool(leaderPath); clt2.exitLeaderElectionParticipantPool(leaderPath); Assert.assertNull(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2)); clt1.close(); clt2.close(); System.out.println("END TestLeaderElection.testElectionPoolMembership"); } @Test(dependsOnMethods = "testElectionPoolMembership") public void testLeadershipListener() throws Exception { System.out.println("START TestLeaderElection.testLeadershipListener"); String leaderPath = LEADER_PATH + "/testLeadershipListener"; // create 2 clients representing 2 participants LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1); LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2); LeaderElectionClient clt3 = createLeaderElectionClient(PARTICIPANT_NAME2); final int count = 10; final int[] numNewLeaderEvent = {0}; final int[] numLeaderGoneEvent = {0}; CountDownLatch countDownLatchNewLeader = new CountDownLatch(count * 2); CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count * 2); LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() { @Override public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) { if (type == ChangeType.LEADER_LOST) { countDownLatchLeaderGone.countDown(); Assert.assertEquals(curLeader.length(), 0); numLeaderGoneEvent[0]++; } else if (type == ChangeType.LEADER_ACQUIRED) { countDownLatchNewLeader.countDown(); numNewLeaderEvent[0]++; Assert.assertTrue(curLeader.length() != 0); } else { Assert.fail(); } } }; clt3.subscribeLeadershipChanges(leaderPath, listener); // each iteration will be participant_1 is new leader, leader gone, participant_2 is new leader, leader gone for (int i = 0; i < count; ++i) { joinPoolTestHelper(leaderPath, clt1, clt2); Thread.sleep(1000); } Assert.assertTrue(countDownLatchNewLeader.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS)); Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS)); Assert.assertEquals(numLeaderGoneEvent[0], count * 2); Assert.assertEquals(numNewLeaderEvent[0], count * 2); clt3.unsubscribeLeadershipChanges(leaderPath, listener); // listener shouldn't receive any event after unsubscribe joinPoolTestHelper(leaderPath, clt1, clt2); Assert.assertEquals(numLeaderGoneEvent[0], count * 2); Assert.assertEquals(numNewLeaderEvent[0], count * 2); clt1.close(); clt2.close(); clt3.close(); System.out.println("END TestLeaderElection.testLeadershipListener"); } @Test(dependsOnMethods = "testLeadershipListener") public void testRelinquishLeadership() throws Exception { System.out.println("START TestLeaderElection.testRelinquishLeadership"); String leaderPath = LEADER_PATH + "/testRelinquishLeadership"; LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1); LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2); LeaderElectionClient clt3 = createLeaderElectionClient(PARTICIPANT_NAME2); final int count = 1; CountDownLatch countDownLatchNewLeader = new CountDownLatch(count); CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count); LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() { @Override public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) { if (type == ChangeType.LEADER_LOST) { countDownLatchLeaderGone.countDown(); Assert.assertEquals(curLeader.length(), 0); } else if (type == ChangeType.LEADER_ACQUIRED) { countDownLatchNewLeader.countDown(); Assert.assertTrue(curLeader.length() != 0); } else { Assert.fail(); } } }; clt1.joinLeaderElectionParticipantPool(leaderPath); clt2.joinLeaderElectionParticipantPool(leaderPath); clt3.subscribeLeadershipChanges(leaderPath, listener); // clt1 gone clt1.relinquishLeader(leaderPath); // participant 1 should have gone, and a leader gone event is sent Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS)); clt1.exitLeaderElectionParticipantPool(leaderPath); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME2)); }, MetaClientTestUtil.WAIT_DURATION)); clt2.exitLeaderElectionParticipantPool(leaderPath); clt1.close(); clt2.close(); clt3.close(); System.out.println("END TestLeaderElection.testRelinquishLeadership"); } @Test(dependsOnMethods = "testAcquireLeadership") public void testSessionExpire() throws Exception { System.out.println("START TestLeaderElection.testSessionExpire"); String leaderPath = LEADER_PATH + "/_testSessionExpire"; LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1); participantInfo.setSimpleField("Key1", "value1"); LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2); participantInfo2.setSimpleField("Key2", "value2"); LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1); LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2); clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); try { clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); // no op } catch (ConcurrentModificationException ex) { // expected Assert.assertEquals(ex.getClass().getName(), "java.util.ConcurrentModificationException"); } clt2.joinLeaderElectionParticipantPool(leaderPath, participantInfo2); // a leader should be up Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); // session expire and reconnect expireSession((ZkMetaClient) clt1.getMetaClient()); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertNotNull(clt1.getLeaderEntryStat(leaderPath)); Assert.assertNotNull(clt1.getLeader(leaderPath)); // when session recreated, participant info node should maintain Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1"); Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1"); Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2"); Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2"); clt1.close(); clt2.close(); System.out.println("END TestLeaderElection.testSessionExpire"); } @Test(dependsOnMethods = "testSessionExpire") public void testClientDisconnectAndReconnectBeforeExpire() throws Exception { System.out.println("START TestLeaderElection.testClientDisconnectAndReconnectBeforeExpire"); String leaderPath = LEADER_PATH + "/testClientDisconnectAndReconnectBeforeExpire"; LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1); LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2); final int count = 1; CountDownLatch countDownLatchNewLeader = new CountDownLatch(count + 1); CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count); LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() { @Override public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) { if (type == ChangeType.LEADER_LOST) { countDownLatchLeaderGone.countDown(); Assert.assertEquals(curLeader.length(), 0); System.out.println("gone leader"); } else if (type == ChangeType.LEADER_ACQUIRED) { countDownLatchNewLeader.countDown(); Assert.assertTrue(curLeader.length() != 0); System.out.println("new leader"); } else { Assert.fail(); } } }; clt1.subscribeLeadershipChanges(leaderPath, listener); clt1.joinLeaderElectionParticipantPool(leaderPath); clt2.joinLeaderElectionParticipantPool(leaderPath); // check leader node version before we simulate disconnect. Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); int leaderNodeVersion = ((ZkMetaClient) clt1.getMetaClient()).exists(leaderPath + "/LEADER").getVersion(); System.out.println("version " + leaderNodeVersion); // clt1 disconnected and reconnected before session expire simulateZkStateReconnected((ZkMetaClient) clt1.getMetaClient()); Assert.assertTrue(countDownLatchNewLeader.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS)); Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS)); leaderNodeVersion = ((ZkMetaClient) clt2.getMetaClient()).exists(leaderPath + "/LEADER").getVersion(); System.out.println("version " + leaderNodeVersion); clt1.exitLeaderElectionParticipantPool(leaderPath); clt2.exitLeaderElectionParticipantPool(leaderPath); clt1.close(); clt2.close(); System.out.println("END TestLeaderElection.testClientDisconnectAndReconnectBeforeExpire"); } private void joinPoolTestHelper(String leaderPath, LeaderElectionClient clt1, LeaderElectionClient clt2) throws Exception { clt1.joinLeaderElectionParticipantPool(leaderPath); clt2.joinLeaderElectionParticipantPool(leaderPath); Thread.sleep(2000); // clt1 gone clt1.exitLeaderElectionParticipantPool(leaderPath); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath) != null); }, MetaClientTestUtil.WAIT_DURATION)); Assert.assertTrue(MetaClientTestUtil.verify(() -> { return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME2)); }, MetaClientTestUtil.WAIT_DURATION)); clt2.exitLeaderElectionParticipantPool(leaderPath); } }
9,241
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClientCache.java
package org.apache.helix.metaclient.impl.zk; /* * 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.metaclient.api.ChildChangeListener; import org.apache.helix.metaclient.api.MetaClientCacheInterface; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.factories.MetaClientCacheConfig; import org.apache.helix.metaclient.impl.zk.adapter.ChildListenerAdapter; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.zookeeper.zkclient.ZkClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ZkMetaClientCache<T> extends ZkMetaClient<T> implements MetaClientCacheInterface<T> { private ConcurrentHashMap<String, T> _dataCacheMap; private final String _rootEntry; private TrieNode _childrenCacheTree; private ChildChangeListener _eventListener; private boolean _cacheData; private boolean _cacheChildren; private static final Logger LOG = LoggerFactory.getLogger(ZkMetaClientCache.class); private ZkClient _cacheClient; private ExecutorService executor; // TODO: Look into using conditional variable instead of latch. private final CountDownLatch _initializedCache = new CountDownLatch(1); /** * Constructor for ZkMetaClientCache. * @param config ZkMetaClientConfig * @param cacheConfig MetaClientCacheConfig */ public ZkMetaClientCache(ZkMetaClientConfig config, MetaClientCacheConfig cacheConfig) { super(config); _cacheClient = getZkClient(); _rootEntry = cacheConfig.getRootEntry(); _cacheData = cacheConfig.getCacheData(); _cacheChildren = cacheConfig.getCacheChildren(); if (_cacheData) { _dataCacheMap = new ConcurrentHashMap<>(); } if (_cacheChildren) { _childrenCacheTree = new TrieNode(_rootEntry, _rootEntry.substring(1)); } } /** * Get data for a given key. * If datacache is enabled, will fetch for cache. If it doesn't exist * returns null (for when initial populating cache is in progress). * @param key key to identify the entry * @return data for the key */ @Override public T get(final String key) { if (_cacheData) { T data = getDataCacheMap().get(key); if (data == null) { LOG.debug("Data not found in cache for key: {}. This could be because the cache is still being populated.", key); } return data; } return super.get(key); } @Override public List<T> get(List<String> keys) { List<T> dataList = new ArrayList<>(); for (String key : keys) { dataList.add(get(key)); } return dataList; } /** * Get the direct children for a given key. * @param key For metadata storage that has hierarchical key space (e.g. ZK), the key would be * a parent key, * For metadata storage that has non-hierarchical key space (e.g. etcd), the key would * be a prefix key. * @return list of direct children or null if key doesn't exist / cache is not populated yet. */ @Override public List<String> getDirectChildrenKeys(final String key) { if (_cacheChildren) { TrieNode node = _childrenCacheTree.processPath(key, true); if (node == null) { LOG.debug("Children not found in cache for key: {}. This could be because the cache is still being populated.", key); return null; } return List.copyOf(node.getChildren().keySet()); } return super.getDirectChildrenKeys(key); } /** * Get the number of direct children for a given key. * @param key For metadata storage that has hierarchical key space (e.g. ZK), the key would be * a parent key, * For metadata storage that has non-hierarchical key space (e.g. etcd), the key would * be a prefix key. * @return number of direct children or 0 if key doesn't exist / has no children / cache is not populated yet. */ @Override public int countDirectChildren(final String key) { if (_cacheChildren) { TrieNode node = _childrenCacheTree.processPath(key, true); if (node == null) { LOG.debug("Children not found in cache for key: {}. This could be because the cache is still being populated.", key); return 0; } return node.getChildren().size(); } return super.countDirectChildren(key); } private void populateAllCache() { // TODO: Concurrently populate children and data cache. if (!_cacheClient.exists(_rootEntry)) { LOG.warn("Root entry: {} does not exist.", _rootEntry); // Let the other threads know that the cache is populated. _initializedCache.countDown(); return; } Queue<String> queue = new ArrayDeque<>(); queue.add(_rootEntry); while (!queue.isEmpty()) { String node = queue.poll(); if (_cacheData) { T dataRecord = _cacheClient.readData(node, true); _dataCacheMap.put(node, dataRecord); } if (_cacheChildren) { _childrenCacheTree.processPath(node, true); } List<String> childNodes = _cacheClient.getChildren(node); for (String child : childNodes) { queue.add(node + "/" + child); // Add child nodes to the queue with their full path. } } // Let the other threads know that the cache is populated. _initializedCache.countDown(); } private class CacheUpdateRunnable implements Runnable { private final String path; private final ChildChangeListener.ChangeType changeType; public CacheUpdateRunnable(String path, ChildChangeListener.ChangeType changeType) { this.path = path; this.changeType = changeType; } @Override public void run() { waitForPopulateAllCache(); // TODO: HANDLE DEDUP EVENT CHANGES switch (changeType) { case ENTRY_CREATED: _childrenCacheTree.processPath(path, true); modifyDataInCache(path, false); break; case ENTRY_DELETED: _childrenCacheTree.processPath(path, false); modifyDataInCache(path, true); break; case ENTRY_DATA_CHANGE: modifyDataInCache(path, false); break; default: LOG.error("Unknown change type: " + changeType); } } } private void waitForPopulateAllCache() { try { _initializedCache.await(); } catch (InterruptedException e) { throw new MetaClientException("Interrupted while waiting for cache to populate.", e); } } private void modifyDataInCache(String path, Boolean isDelete) { if (_cacheData) { if (isDelete) { getDataCacheMap().remove(path); } else { T dataRecord = _cacheClient.readData(path, true); getDataCacheMap().put(path, dataRecord); } } } public ConcurrentHashMap<String, T> getDataCacheMap() { return _dataCacheMap; } /** * Connect to the underlying ZkClient. */ @Override public void connect() { super.connect(); _eventListener = (path, changeType) -> { Runnable cacheUpdateRunnable = new CacheUpdateRunnable(path, changeType); executor.execute(cacheUpdateRunnable); }; executor = Executors.newSingleThreadExecutor(); _cacheClient.subscribePersistRecursiveListener(_rootEntry, new ChildListenerAdapter(_eventListener)); populateAllCache(); } }
9,242
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
package org.apache.helix.metaclient.impl.zk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.helix.metaclient.api.AsyncCallback; import org.apache.helix.metaclient.api.ChildChangeListener; import org.apache.helix.metaclient.api.ConnectStateChangeListener; import org.apache.helix.metaclient.api.DataChangeListener; import org.apache.helix.metaclient.api.DataUpdater; import org.apache.helix.metaclient.api.DirectChildChangeListener; import org.apache.helix.metaclient.api.DirectChildSubscribeResult; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.api.Op; import org.apache.helix.metaclient.api.OpResult; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.exception.MetaClientNoNodeException; import org.apache.helix.metaclient.exception.MetaClientNodeExistsException; import org.apache.helix.metaclient.impl.zk.adapter.ChildListenerAdapter; import org.apache.helix.metaclient.impl.zk.adapter.DataListenerAdapter; import org.apache.helix.metaclient.impl.zk.adapter.DirectChildListenerAdapter; import org.apache.helix.metaclient.impl.zk.adapter.StateChangeListenerAdapter; import org.apache.helix.metaclient.impl.zk.adapter.ZkMetaClientCreateCallbackHandler; import org.apache.helix.metaclient.impl.zk.adapter.ZkMetaClientDeleteCallbackHandler; import org.apache.helix.metaclient.impl.zk.adapter.ZkMetaClientExistCallbackHandler; import org.apache.helix.metaclient.impl.zk.adapter.ZkMetaClientGetCallbackHandler; import org.apache.helix.metaclient.impl.zk.adapter.ZkMetaClientSetCallbackHandler; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil; import org.apache.helix.zookeeper.api.client.ChildrenSubscribeResult; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.helix.zookeeper.zkclient.IZkStateListener; import org.apache.helix.zookeeper.zkclient.ZkConnection; import org.apache.helix.zookeeper.zkclient.exception.ZkException; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil.separateIntoUniqueNodePaths; import static org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil.translateZkExceptionToMetaclientException; public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(ZkMetaClient.class); private final ZkClient _zkClient; private final long _initConnectionTimeout; private final long _reconnectTimeout; // After ZkClient gets disconnected from ZK server, it keeps retrying connection until connection // is re-established or ZkClient is closed. We need a separate thread to monitor ZkClient // reconnect and close ZkClient if it not able to reconnect within user specified timeout. private final ScheduledExecutorService _zkClientReconnectMonitor; private ScheduledFuture<?> _reconnectMonitorFuture; private ReconnectStateChangeListener _reconnectStateChangeListener; // Lock all activities related to ZkClient connection private ReentrantLock _zkClientConnectionMutex = new ReentrantLock(); public ZkMetaClient(ZkMetaClientConfig config) { _initConnectionTimeout = config.getConnectionInitTimeoutInMillis(); _reconnectTimeout = config.getMetaClientReconnectPolicy().getAutoReconnectTimeout(); // TODO: Right new ZkClient reconnect using exp backoff with fixed max backoff interval. We should // Allow user to config reconnect policy _zkClient = new ZkClient(new ZkConnection(config.getConnectionAddress(), (int) config.getSessionTimeoutInMillis()), (int) _initConnectionTimeout, _reconnectTimeout /*use reconnect timeout for retry timeout*/, config.getZkSerializer(), config.getMonitorType(), config.getMonitorKey(), config.getMonitorInstanceName(), config.getMonitorRootPathOnly(), false, true); _zkClientReconnectMonitor = Executors.newSingleThreadScheduledExecutor(); _reconnectStateChangeListener = new ReconnectStateChangeListener(); } @Override public void create(String key, Object data) { try { create(key, data, EntryMode.PERSISTENT); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } @Override public void create(String key, Object data, EntryMode mode) { try { _zkClient.create(key, data, ZkMetaClientUtil.convertMetaClientMode(mode)); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } catch (KeeperException e) { throw new MetaClientException(e); } } @Override public void recursiveCreate(String key, T data, EntryMode mode) { // Function named recursiveCreate to match naming scheme, but actual work is iterative iterativeCreate(key, data, mode, -1); } @Override public void recursiveCreateWithTTL(String key, T data, long ttl) { iterativeCreate(key, data, EntryMode.TTL, ttl); } private void iterativeCreate(String key, T data, EntryMode mode, long ttl) { List<String> nodePaths = separateIntoUniqueNodePaths(key); int i = 0; // Ephemeral nodes cant have children, so change mode when creating parents EntryMode parentMode = (EntryMode.EPHEMERAL.equals(mode) ? EntryMode.PERSISTENT : mode); // Iterate over paths, starting with full key then attempting each successive parent // Try /a/b/c, if parent /a/b, does not exist, then try to create parent, etc.. while (i < nodePaths.size()) { // If parent exists or there is no parent node, then try to create the node // and break out of loop on successful create if (i == nodePaths.size() - 1 || _zkClient.exists(nodePaths.get(i+1))) { try { if (EntryMode.TTL.equals(mode)) { createWithTTL(nodePaths.get(i), data, ttl); } else { create(nodePaths.get(i), data, i == 0 ? mode : parentMode); } // Race condition may occur where a node is created by another thread in between loops. // We should not throw error if this occurs for parent nodes, only for the full node path. } catch (MetaClientNodeExistsException e) { if (i == 0) { throw e; } } break; // Else try to create parent in next loop iteration } else { i++; } } // Reattempt creation of children that failed due to parent not existing while (--i >= 0) { try { if (EntryMode.TTL.equals(mode)) { createWithTTL(nodePaths.get(i), data, ttl); } else { create(nodePaths.get(i), data, i == 0 ? mode : parentMode); } // Catch same race condition as above } catch (MetaClientNodeExistsException e) { if (i == 0) { throw e; } } } } @Override public void createWithTTL(String key, T data, long ttl) { try { _zkClient.createPersistentWithTTL(key, data, ttl); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } @Override public void renewTTLNode(String key) { T oldData = get(key); if (oldData == null) { throw new MetaClientNoNodeException("Node at " + key + " does not exist."); } set(key, oldData, _zkClient.getStat(key).getVersion()); } @Override public void set(String key, T data, int version) { try { _zkClient.writeData(key, data, version); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } @Override public T update(String key, DataUpdater<T> updater) { org.apache.zookeeper.data.Stat stat = new org.apache.zookeeper.data.Stat(); // TODO: add retry logic for ZkBadVersionException. try { T oldData = _zkClient.readData(key, stat); T newData = updater.update(oldData); set(key, newData, stat.getVersion()); return newData; } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } //TODO: Get Expiry Time in Stat @Override public Stat exists(String key) { org.apache.zookeeper.data.Stat zkStats; try { zkStats = _zkClient.getStat(key); if (zkStats == null) { return null; } return ZkMetaClientUtil.convertZkStatToStat(zkStats); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } @Override public T get(String key) { return _zkClient.readData(key, true); } @Override public ImmutablePair<T, Stat> getDataAndStat(final String key) { try { org.apache.zookeeper.data.Stat zkStat = new org.apache.zookeeper.data.Stat(); T data = _zkClient.readData(key, zkStat); return ImmutablePair.of(data, ZkMetaClientUtil.convertZkStatToStat(zkStat)); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } @Override public List<String> getDirectChildrenKeys(String key) { try { return _zkClient.getChildren(key); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } @Override public int countDirectChildren(String key) { return _zkClient.countChildren(key); } @Override public boolean delete(String key) { try { return _zkClient.delete(key); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } } @Override public boolean recursiveDelete(String key) { _zkClient.deleteRecursively(key); return true; } // In Current ZkClient, Async CRUD do auto retry when connection lost or session mismatch using // existing retry handling logic in zkClient. (defined in ZkAsyncCallbacks) // ZkClient execute async callbacks at zkClient main thead, retry is handles in a separate retry // thread. In our first version of implementation, we will keep similar behavior and have // callbacks executed in ZkClient event thread, and reuse zkClient retry logic. // It is highly recommended *NOT* to perform any blocking operation inside the callbacks. // If you block the thread the meta client won't process other events. // corresponding callbacks for each operation are invoked in order. @Override public void setAsyncExecPoolSize(int poolSize) { throw new UnsupportedOperationException("All async calls are executed in a single thread to maintain sequence."); } @Override public void asyncCreate(String key, Object data, EntryMode mode, AsyncCallback.VoidCallback cb) { CreateMode entryMode; try { entryMode = ZkMetaClientUtil.convertMetaClientMode(mode); } catch (ZkException | KeeperException e) { throw new MetaClientException(e); } _zkClient.asyncCreate(key, data, entryMode, new ZkMetaClientCreateCallbackHandler(cb)); } @Override public void asyncUpdate(String key, DataUpdater<T> updater, AsyncCallback.DataCallback cb) { throw new NotImplementedException("Currently asyncUpdate is not supported in ZkMetaClient."); /* * TODO: Only Helix has potential using this API as of now. (ZkBaseDataAccessor.update()) * Will move impl from ZkBaseDataAccessor to here when retiring ZkBaseDataAccessor. */ } @Override public void asyncGet(String key, AsyncCallback.DataCallback cb) { _zkClient.asyncGetData(key, new ZkMetaClientGetCallbackHandler(cb)); } @Override public void asyncCountChildren(String key, AsyncCallback.DataCallback cb) { throw new NotImplementedException("Currently asyncCountChildren is not supported in ZkMetaClient."); /* * TODO: Only Helix has potential using this API as of now. (ZkBaseDataAccessor.getChildren()) * Will move impl from ZkBaseDataAccessor to here when retiring ZkBaseDataAccessor. */ } @Override public void asyncExist(String key, AsyncCallback.StatCallback cb) { _zkClient.asyncExists(key, new ZkMetaClientExistCallbackHandler(cb)); } public void asyncDelete(String key, AsyncCallback.VoidCallback cb) { _zkClient.asyncDelete(key, new ZkMetaClientDeleteCallbackHandler(cb)); } @Override public void asyncTransaction(Iterable<Op> ops, AsyncCallback.TransactionCallback cb) { throw new NotImplementedException("Currently asyncTransaction is not supported in ZkMetaClient."); //TODO: There is no active use case for Async transaction. } @Override public void asyncSet(String key, T data, int version, AsyncCallback.StatCallback cb) { _zkClient.asyncSetData(key, data, version, new ZkMetaClientSetCallbackHandler(cb)); } @Override public void connect() { try { _zkClientConnectionMutex.lock(); _zkClient.connect(_initConnectionTimeout, _zkClient); // register _reconnectStateChangeListener as state change listener to react to ZkClient connect // state change event. When ZkClient disconnected from ZK, it still auto reconnect until // ZkClient is closed or connection re-established. // We will need to close ZkClient when user set retry connection timeout. _zkClient.subscribeStateChanges(_reconnectStateChangeListener); } catch (ZkException e) { throw translateZkExceptionToMetaclientException(e); } finally { _zkClientConnectionMutex.unlock(); } } @Override public void disconnect() { cleanUpAndClose(true, true); _zkClientReconnectMonitor.shutdownNow(); } @Override public ConnectState getClientConnectionState() { return null; } @Override public boolean subscribeDataChange(String key, DataChangeListener listener, boolean skipWatchingNonExistNode) { _zkClient.subscribeDataChanges(key, new DataListenerAdapter(listener)); return true; } @Override public DirectChildSubscribeResult subscribeDirectChildChange(String key, DirectChildChangeListener listener, boolean skipWatchingNonExistNode) { ChildrenSubscribeResult result = _zkClient.subscribeChildChanges(key, new DirectChildListenerAdapter(listener), skipWatchingNonExistNode); return new DirectChildSubscribeResult(result.getChildren(), result.isInstalled()); } @Override public boolean subscribeStateChanges(ConnectStateChangeListener listener) { _zkClient.subscribeStateChanges(new StateChangeListenerAdapter(listener)); return true; } @Override public boolean subscribeChildChanges(String key, ChildChangeListener listener, boolean skipWatchingNonExistNode) { if (skipWatchingNonExistNode && exists(key) == null) { return false; } _zkClient.subscribePersistRecursiveListener(key, new ChildListenerAdapter(listener)); return true; } @Override public void unsubscribeDataChange(String key, DataChangeListener listener) { _zkClient.unsubscribeDataChanges(key, new DataListenerAdapter(listener)); } @Override public void unsubscribeDirectChildChange(String key, DirectChildChangeListener listener) { _zkClient.unsubscribeChildChanges(key, new DirectChildListenerAdapter(listener)); } // TODO: add impl and remove UnimplementedException @Override public void unsubscribeChildChanges(String key, ChildChangeListener listener) { _zkClient.unsubscribePersistRecursiveListener(key, new ChildListenerAdapter(listener)); } @Override public void unsubscribeConnectStateChanges(ConnectStateChangeListener listener) { _zkClient.subscribeStateChanges(new StateChangeListenerAdapter(listener)); } @Override public boolean waitUntilExists(String key, TimeUnit timeUnit, long time) { return false; } @Override public boolean[] create(List<String> key, List<T> data, List<EntryMode> mode) { return new boolean[0]; } @Override public boolean[] create(List<String> key, List<T> data) { return new boolean[0]; } @Override public boolean[] delete(List<String> keys) { return new boolean[0]; } @Override public List<Stat> exists(List<String> keys) { return null; } @Override public List<T> get(List<String> keys) { return null; } @Override public List<T> update(List<String> keys, List<DataUpdater<T>> updater) { return null; } @Override public boolean[] set(List<String> keys, List<T> datas, List<Integer> version) { return new boolean[0]; } @Override public void close() { disconnect(); } @Override public boolean isClosed() { return _zkClient.isClosed(); } @Override public List<OpResult> transactionOP(Iterable<Op> ops) { // Convert list of MetaClient Ops to Zk Ops List<org.apache.zookeeper.Op> zkOps = ZkMetaClientUtil.metaClientOpsToZkOps(ops); // Execute Zk transactional support List<org.apache.zookeeper.OpResult> zkResult = _zkClient.multi(zkOps); // Convert list of Zk OpResults to MetaClient OpResults return ZkMetaClientUtil.zkOpResultToMetaClientOpResults(zkResult); } @Override public byte[] serialize(T data, String path) { return _zkClient.serialize(data, path); } @Override public T deserialize(byte[] bytes, String path) { return _zkClient.deserialize(bytes, path); } /** * A clean up method called when connect state change or MetaClient is closing. * @param cancel If we want to cancel the reconnect monitor thread. * @param close If we want to close ZkClient. */ private void cleanUpAndClose(boolean cancel, boolean close) { _zkClientConnectionMutex.lock(); try { if (close && !_zkClient.isClosed()) { _zkClient.close(); // TODO: need to unsubscribe all persist watcher from ZK // Add this in ZkClient when persist watcher change is in // Also need to manually send CLOSED state change to state // change listener (in change adapter) LOG.info("ZkClient is closed"); } if (cancel && _reconnectMonitorFuture != null) { _reconnectMonitorFuture.cancel(true); LOG.info("ZkClient reconnect monitor thread is canceled"); } } finally { _zkClientConnectionMutex.unlock(); } } /** * MetaClient uses Helix ZkClient (@see org.apache.helix.zookeeper.impl.client.ZkClient) to connect * to ZK. Current implementation of ZkClient auto-reconnects infinitely. We use monitor thread * in ZkMetaClient to monitor reconnect status and close ZkClient when the client still is in * disconnected state when it reach reconnect timeout. * * * case 1: Start the monitor thread when ZkMetaClient gets disconnected even to check connect state * when timeout reached. If not re-connected when timed out, kill the monitor thread * and close ZkClient. * [MetaClient thread] --------------------------------------------------------------- * ( When disconnected, schedule a event * to check connect state after timeout) * [Reconnect monitor thread] -------------------------------------- * ^ | not reconnected when timed out * / | * | disconnected event v * [ZkClient] -------X---------------------------------------X zkClient.close() * [ZkClient exp back | X X * -off retry connection] |--------|--------------|-------------- * * * case 2: Start the monitor thread when ZkMetaClient gets disconnected even to check connect state * when timeout reached. If re-connected before timed out, cancel the delayed monitor thread. * * [MetaClient thread] --------------------------------------------------------------- * (cancel scheduled task when reconnected) * [Reconnect monitor] ---------------------------------X * ^ ^ * / / * | disconnected event | reconnected event * [ZkClient] -----X------------------------------------------------------ * [ZkClient exp back | X Y Reconnected before timed out * -off retry connection] |--------| ---------------------| * * * case 3: Start the monitor thread when ZkMetaClient gets disconnected even to check connect state * when timeout reached. If re-connected errored, kill the monitor thread and cancel the * delayed monitor thread. * [MetaClient thread] --------------------------------------------------------------- * (cancel scheduled task and close ZkClient when reconnected error) * [Reconnect monitor] ----------------------------------X * ^ ^ | * / err / | * | disconnected event | v close ZkClient * [ZkClient] -----X-------------------------------X ---X * [ZkClient exp back | X ^ Reconnect error * -off retry connection] |--------| --------------------| * */ private class ReconnectStateChangeListener implements IZkStateListener { // Schedule a monitor to track ZkClient auto reconnect when Disconnected // Cancel the monitor thread when connected. @Override public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception { if (state == Watcher.Event.KeeperState.Disconnected) { // ------case 1 // Expired. start a new event monitoring retry _zkClientConnectionMutex.lockInterruptibly(); try { if (_reconnectMonitorFuture == null || _reconnectMonitorFuture.isCancelled() || _reconnectMonitorFuture.isDone()) { _reconnectMonitorFuture = _zkClientReconnectMonitor.schedule(() -> { if (!_zkClient.getConnection().getZookeeperState().isConnected()) { cleanUpAndClose(false, true); } }, _reconnectTimeout, TimeUnit.MILLISECONDS); LOG.info("ZkClient is Disconnected, schedule a reconnect monitor after {}", _reconnectTimeout); } } finally { _zkClientConnectionMutex.unlock(); } } else if (state == Watcher.Event.KeeperState.SyncConnected || state == Watcher.Event.KeeperState.ConnectedReadOnly) { // ------ case 2 cleanUpAndClose(true, false); LOG.info("ZkClient is SyncConnected, reconnect monitor thread is canceled (if any)"); } } // Cancel the monitor thread when connected. @Override public void handleNewSession(String sessionId) throws Exception { // ------ case 2 cleanUpAndClose(true, false); LOG.info("New session initiated in ZkClient, reconnect monitor thread is canceled (if any)"); } // Cancel the monitor thread and close ZkClient when connect error. @Override public void handleSessionEstablishmentError(Throwable error) throws Exception { // -- case 3 cleanUpAndClose(true, true); LOG.info("New session initiated in ZkClient, reconnect monitor thread is canceled (if any)"); } } @VisibleForTesting ZkClient getZkClient() { return _zkClient; } }
9,243
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
package org.apache.helix.metaclient.impl.zk.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.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.api.OpResult; import org.apache.helix.metaclient.exception.MetaClientBadVersionException; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.exception.MetaClientInterruptException; import org.apache.helix.metaclient.exception.MetaClientNoNodeException; import org.apache.helix.metaclient.exception.MetaClientTimeoutException; import org.apache.helix.metaclient.exception.MetaClientNodeExistsException; import org.apache.helix.zookeeper.zkclient.exception.ZkBadVersionException; import org.apache.helix.zookeeper.zkclient.exception.ZkException; import org.apache.helix.zookeeper.zkclient.exception.ZkInterruptedException; import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException; import org.apache.helix.zookeeper.zkclient.exception.ZkNodeExistsException; import org.apache.helix.zookeeper.zkclient.exception.ZkTimeoutException; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.server.EphemeralType; public class ZkMetaClientUtil { //TODO Implement MetaClient ACL //Default ACL value until metaClient Op has ACL of its own. private static final List<ACL> DEFAULT_ACL = Collections.unmodifiableList(ZooDefs.Ids.OPEN_ACL_UNSAFE); private ZkMetaClientUtil() { } /** * Helper function for transactionOp. Converts MetaClient Op's into Zk Ops to execute * zk transactional support. * @param ops * @return */ public static List<Op> metaClientOpsToZkOps(Iterable<org.apache.helix.metaclient.api.Op> ops) { List<Op> zkOps = new ArrayList<>(); for (org.apache.helix.metaclient.api.Op op : ops) { Function<org.apache.helix.metaclient.api.Op, Op> function = getOpMap().get(op.getType()); if (function != null) { zkOps.add(function.apply(op)); } else { throw new IllegalArgumentException("Op type " + op.getType().name() + " is not supported."); } } return zkOps; } private static final class OpMapHolder { static final Map<org.apache.helix.metaclient.api.Op.Type, Function<org.apache.helix.metaclient.api.Op, Op>> OPMAP = initializeOpMap(); private static Map<org.apache.helix.metaclient.api.Op.Type, Function<org.apache.helix.metaclient.api.Op, Op>> initializeOpMap() { Map<org.apache.helix.metaclient.api.Op.Type, Function<org.apache.helix.metaclient.api.Op, Op>> opmap = new EnumMap<>(org.apache.helix.metaclient.api.Op.Type.class); opmap.put(org.apache.helix.metaclient.api.Op.Type.CREATE, op -> { try { CreateMode mode = convertMetaClientMode( ((org.apache.helix.metaclient.api.Op.Create) op).getEntryMode()); return Op.create(op.getPath(), ((org.apache.helix.metaclient.api.Op.Create) op).getData(), DEFAULT_ACL, mode); } catch (KeeperException e) { throw translateZkExceptionToMetaclientException(ZkException.create(e)); } }); opmap.put(org.apache.helix.metaclient.api.Op.Type.DELETE, op -> Op .delete(op.getPath(), ((org.apache.helix.metaclient.api.Op.Delete) op).getVersion())); opmap.put(org.apache.helix.metaclient.api.Op.Type.SET, op -> Op .setData(op.getPath(), ((org.apache.helix.metaclient.api.Op.Set) op).getData(), ((org.apache.helix.metaclient.api.Op.Set) op).getVersion())); opmap.put(org.apache.helix.metaclient.api.Op.Type.CHECK, op -> Op .check(op.getPath(), ((org.apache.helix.metaclient.api.Op.Check) op).getVersion())); return opmap; } } private static Map<org.apache.helix.metaclient.api.Op.Type, Function<org.apache.helix.metaclient.api.Op, Op>> getOpMap() { return OpMapHolder.OPMAP; } public static CreateMode convertMetaClientMode(MetaClientInterface.EntryMode entryMode) throws KeeperException { switch (entryMode) { case PERSISTENT: return CreateMode.PERSISTENT; case EPHEMERAL: return CreateMode.EPHEMERAL; case CONTAINER: return CreateMode.CONTAINER; default: throw new IllegalArgumentException(entryMode.name() + " is not a supported EntryMode."); } } /** * Helper function for transactionOP. Converts the result from calling zk transactional support into * metaclient OpResults. * @param zkResult * @return */ public static List<OpResult> zkOpResultToMetaClientOpResults(List<org.apache.zookeeper.OpResult> zkResult) { List<OpResult> metaClientOpResult = new ArrayList<>(); for (org.apache.zookeeper.OpResult opResult : zkResult) { Function<org.apache.zookeeper.OpResult, OpResult> function = getOpResultMap().get(opResult.getClass()); if (function != null) { metaClientOpResult.add(function.apply(opResult)); } else { throw new IllegalArgumentException( "OpResult type " + opResult.getType() + "is not supported."); } } return metaClientOpResult; } private static final class OpResultMapHolder { static final Map<Class<? extends org.apache.zookeeper.OpResult>, Function<org.apache.zookeeper.OpResult, OpResult>> OPRESULTMAP = initializeOpResultMap(); private static Map<Class<? extends org.apache.zookeeper.OpResult>, Function<org.apache.zookeeper.OpResult, OpResult>> initializeOpResultMap() { Map<Class<? extends org.apache.zookeeper.OpResult>, Function<org.apache.zookeeper.OpResult, OpResult>> opResultMap = new HashMap<>(); opResultMap.put(org.apache.zookeeper.OpResult.CreateResult.class, opResult -> { org.apache.zookeeper.OpResult.CreateResult zkOpCreateResult = (org.apache.zookeeper.OpResult.CreateResult) opResult; if (opResult.getType() == 1) { return new OpResult.CreateResult(zkOpCreateResult.getPath()); } else { MetaClientInterface.Stat metaClientStat = new MetaClientInterface.Stat( convertZkEntryModeToMetaClientEntryMode( zkOpCreateResult.getStat().getEphemeralOwner()), zkOpCreateResult.getStat().getVersion()); return new OpResult.CreateResult(zkOpCreateResult.getPath(), metaClientStat); } }); opResultMap.put(org.apache.zookeeper.OpResult.DeleteResult.class, opResult -> new OpResult.DeleteResult()); opResultMap.put(org.apache.zookeeper.OpResult.GetDataResult.class, opResult -> { org.apache.zookeeper.OpResult.GetDataResult zkOpGetDataResult = (org.apache.zookeeper.OpResult.GetDataResult) opResult; MetaClientInterface.Stat metaClientStat = new MetaClientInterface.Stat( convertZkEntryModeToMetaClientEntryMode( zkOpGetDataResult.getStat().getEphemeralOwner()), zkOpGetDataResult.getStat().getVersion()); return new OpResult.GetDataResult(zkOpGetDataResult.getData(), metaClientStat); }); opResultMap.put(org.apache.zookeeper.OpResult.SetDataResult.class, opResult -> { org.apache.zookeeper.OpResult.SetDataResult zkOpSetDataResult = (org.apache.zookeeper.OpResult.SetDataResult) opResult; MetaClientInterface.Stat metaClientStat = new MetaClientInterface.Stat( convertZkEntryModeToMetaClientEntryMode( zkOpSetDataResult.getStat().getEphemeralOwner()), zkOpSetDataResult.getStat().getVersion()); return new OpResult.SetDataResult(metaClientStat); }); opResultMap.put(org.apache.zookeeper.OpResult.GetChildrenResult.class, opResult -> new OpResult.GetChildrenResult( ((org.apache.zookeeper.OpResult.GetChildrenResult) opResult).getChildren())); opResultMap.put(org.apache.zookeeper.OpResult.CheckResult.class, opResult -> new OpResult.CheckResult()); opResultMap.put(org.apache.zookeeper.OpResult.ErrorResult.class, opResult -> new OpResult.ErrorResult( ((org.apache.zookeeper.OpResult.ErrorResult) opResult).getErr())); return opResultMap; } } private static Map<Class<? extends org.apache.zookeeper.OpResult>, Function<org.apache.zookeeper.OpResult, OpResult>> getOpResultMap() { return OpResultMapHolder.OPRESULTMAP; } public static MetaClientInterface.EntryMode convertZkEntryModeToMetaClientEntryMode( long ephemeralOwner) { EphemeralType zkEphemeralType = EphemeralType.get(ephemeralOwner); switch (zkEphemeralType) { case VOID: return MetaClientInterface.EntryMode.PERSISTENT; case CONTAINER: return MetaClientInterface.EntryMode.CONTAINER; case NORMAL: return MetaClientInterface.EntryMode.EPHEMERAL; case TTL: return MetaClientInterface.EntryMode.TTL; default: throw new IllegalArgumentException(zkEphemeralType + " is not supported."); } } public static MetaClientException translateZkExceptionToMetaclientException(ZkException e) { if (e instanceof ZkNoNodeException) { return new MetaClientNoNodeException(e); } else if (e instanceof ZkBadVersionException) { return new MetaClientBadVersionException(e); } else if (e instanceof ZkTimeoutException) { return new MetaClientTimeoutException(e); } else if (e instanceof ZkInterruptedException) { return new MetaClientInterruptException(e); } else if (e instanceof ZkNodeExistsException) { return new MetaClientNodeExistsException(e); } return new MetaClientException(e); } public static MetaClientInterface.ConnectState translateKeeperStateToMetaClientConnectState( Watcher.Event.KeeperState keeperState) { if (keeperState == null) return MetaClientInterface.ConnectState.NOT_CONNECTED; switch (keeperState) { case AuthFailed: return MetaClientInterface.ConnectState.AUTH_FAILED; case Closed: return MetaClientInterface.ConnectState.CLOSED_BY_CLIENT; case Disconnected: return MetaClientInterface.ConnectState.DISCONNECTED; case Expired: return MetaClientInterface.ConnectState.EXPIRED; case SaslAuthenticated: return MetaClientInterface.ConnectState.AUTHENTICATED; case SyncConnected: case ConnectedReadOnly: return MetaClientInterface.ConnectState.CONNECTED; default: throw new IllegalArgumentException(keeperState + " is not a supported."); } } public static MetaClientInterface.Stat convertZkStatToStat( org.apache.zookeeper.data.Stat zkStat) { return new MetaClientInterface.Stat( convertZkEntryModeToMetaClientEntryMode(zkStat.getEphemeralOwner()), zkStat.getVersion(), zkStat.getCtime(), zkStat.getMtime(), EphemeralType.TTL.getValue(zkStat.getEphemeralOwner())); } /** * This function translate and group Zk exception code to metaclient code. * It currently includes all ZK code on 3.6.3. */ public static MetaClientException.ReturnCode translateZooKeeperCodeToMetaClientCode( KeeperException.Code zkCode) { // TODO: add log to track ZK origional code. switch (zkCode) { case AUTHFAILED: case SESSIONCLOSEDREQUIRESASLAUTH: case INVALIDACL: return MetaClientException.ReturnCode.AUTH_FAILED; case CONNECTIONLOSS: return MetaClientException.ReturnCode.CONNECTION_LOSS; case BADARGUMENTS: return MetaClientException.ReturnCode.INVALID_ARGUMENTS; case BADVERSION: return MetaClientException.ReturnCode.BAD_VERSION; case NOAUTH: return MetaClientException.ReturnCode.NO_AUTH; case NOWATCHER: return MetaClientException.ReturnCode.INVALID_LISTENER; case NOTEMPTY: return MetaClientException.ReturnCode.NOT_LEAF_ENTRY; case NODEEXISTS: return MetaClientException.ReturnCode.ENTRY_EXISTS; case SESSIONEXPIRED: case SESSIONMOVED: case UNKNOWNSESSION: return MetaClientException.ReturnCode.SESSION_ERROR; case NONODE: return MetaClientException.ReturnCode.NO_SUCH_ENTRY; case OPERATIONTIMEOUT: return MetaClientException.ReturnCode.OPERATION_TIMEOUT; case OK: return MetaClientException.ReturnCode.OK; case UNIMPLEMENTED: return MetaClientException.ReturnCode.UNIMPLEMENTED; case RUNTIMEINCONSISTENCY: case DATAINCONSISTENCY: return MetaClientException.ReturnCode.CONSISTENCY_ERROR; case SYSTEMERROR: case MARSHALLINGERROR: case NEWCONFIGNOQUORUM: case RECONFIGINPROGRESS: return MetaClientException.ReturnCode.DB_SYSTEM_ERROR; case NOCHILDRENFOREPHEMERALS: case INVALIDCALLBACK: case NOTREADONLY: case EPHEMERALONLOCALSESSION: case RECONFIGDISABLED: return MetaClientException.ReturnCode.DB_USER_ERROR; /* * APIERROR is ZooKeeper Code value separator. It is never thrown by ZK server, * ZK error codes greater than its value are user or client errors and values less than * this indicate a ZK server. * Note: there are some mismatch between ZK doc and Zk code intValue define. We are comparing * ordinal instead of using intValue(). * https://zookeeper.apache.org/doc/r3.6.2/apidocs/zookeeper-server/index.html?org/apache/zookeeper/KeeperException.Code.html */ default: if (zkCode.ordinal() < KeeperException.Code.APIERROR.ordinal() && zkCode.ordinal() >= KeeperException.Code.SYSTEMERROR.ordinal()) { return MetaClientException.ReturnCode.DB_SYSTEM_ERROR; } return MetaClientException.ReturnCode.DB_USER_ERROR; } } // Returns null if no parent path public static String getZkParentPath(String path) { int idx = path.lastIndexOf('/'); return idx == 0 ? null : path.substring(0, idx); } // Splits a path into the paths for each node along the way. // /a/b/c --> /a/b/c, /a/b, /a public static List<String> separateIntoUniqueNodePaths(String path) { if (path == null || "/".equals(path)) { return null; } String[] subPath = path.split("/"); String[] nodePaths = new String[subPath.length-1]; StringBuilder tempPath = new StringBuilder(); for (int i = 1; i < subPath.length; i++) { tempPath.append( "/"); tempPath.append(subPath[i]); nodePaths[subPath.length - 1 - i] = tempPath.toString(); } return Arrays.asList(nodePaths); } }
9,244
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/ZkMetaClientDeleteCallbackHandler.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * 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.metaclient.api.AsyncCallback; import org.apache.helix.zookeeper.zkclient.callback.ZkAsyncCallbacks; /** * Wrapper class for metaclient.api.AsyncCallback. * This wrapper class extends zk callback class. It has an object of user defined * metaclient.api.AsyncCallback. * Each callback will do default retry defined in ZkAsyncCallbacks. (defined in ZkAsyncCallbacks) * * ZkClient execute async callbacks at zkClient main thead, retry is handles in a separate retry * thread. In our first version of implementation, we will keep similar behavior and have * callbacks executed in ZkClient event thread, and reuse zkclient retry logic. */ public class ZkMetaClientDeleteCallbackHandler extends ZkAsyncCallbacks.DeleteCallbackHandler { AsyncCallback.VoidCallback _userCallback; public ZkMetaClientDeleteCallbackHandler(AsyncCallback.VoidCallback cb) { _userCallback = cb; } @Override public void handle() { _userCallback.processResult(getRc(), getPath()); } }
9,245
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/ZkMetaClientCreateCallbackHandler.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * 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.metaclient.api.AsyncCallback; import org.apache.helix.zookeeper.zkclient.callback.ZkAsyncCallbacks; /** * Wrapper class for metaclient.api.AsyncCallback. * This wrapper class extends zk callback class. It has an object of user defined * metaclient.api.AsyncCallback. * Each callback will do default retry defined in ZkAsyncCallbacks. (defined in ZkAsyncCallbacks) * * ZkClient execute async callbacks at zkClient main thead, retry is handles in a separate retry * thread. In our first version of implementation, we will keep similar behavior and have * callbacks executed in ZkClient event thread, and reuse zkclient retry logic. */ public class ZkMetaClientCreateCallbackHandler extends ZkAsyncCallbacks.CreateCallbackHandler { AsyncCallback.VoidCallback _userCallback; public ZkMetaClientCreateCallbackHandler(AsyncCallback.VoidCallback cb) { _userCallback = cb; } @Override public void handle() { _userCallback.processResult(getRc(), getPath()); } }
9,246
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/DirectChildListenerAdapter.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import org.apache.helix.metaclient.api.DirectChildChangeListener; import org.apache.helix.zookeeper.zkclient.IZkChildListener; public class DirectChildListenerAdapter implements IZkChildListener { private final DirectChildChangeListener _listener; public DirectChildListenerAdapter(DirectChildChangeListener listener) { _listener = listener; } @Override public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception { _listener.handleDirectChildChange(parentPath); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DirectChildListenerAdapter that = (DirectChildListenerAdapter) o; return _listener.equals(that._listener); } @Override public int hashCode() { return _listener.hashCode(); } }
9,247
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/ZkMetaClientGetCallbackHandler.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * 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.metaclient.api.AsyncCallback; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil; import org.apache.helix.zookeeper.zkclient.callback.ZkAsyncCallbacks; /** * Wrapper class for metaclient.api.AsyncCallback. * This wrapper class extends zk callback class. It has an object of user defined * metaclient.api.AsyncCallback. * Each callback will do default retry defined in ZkAsyncCallbacks. (defined in ZkAsyncCallbacks) * * ZkClient execute async callbacks at zkClient main thead, retry is handles in a separate retry * thread. In our first version of implementation, we will keep similar behavior and have * callbacks executed in ZkClient event thread, and reuse zkclient retry logic. */ public class ZkMetaClientGetCallbackHandler extends ZkAsyncCallbacks.GetDataCallbackHandler { AsyncCallback.DataCallback _userCallback; public ZkMetaClientGetCallbackHandler(AsyncCallback.DataCallback cb) { _userCallback = cb; } // Call user passed in callback. Will pass a null for stats if get operation fails. @Override public void handle() { _userCallback.processResult(getRc(), getPath(), getData(), getStat() == null ? null : new MetaClientInterface.Stat( ZkMetaClientUtil.convertZkEntryModeToMetaClientEntryMode(getStat().getEphemeralOwner()), getStat().getVersion())); } }
9,248
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/ZkMetaClientSetCallbackHandler.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * 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.metaclient.api.AsyncCallback; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil; import org.apache.helix.zookeeper.zkclient.callback.ZkAsyncCallbacks; public class ZkMetaClientSetCallbackHandler extends ZkAsyncCallbacks.SetDataCallbackHandler { AsyncCallback.StatCallback userCallback; public ZkMetaClientSetCallbackHandler(AsyncCallback.StatCallback cb) { userCallback = cb; } @Override public void handle() { userCallback.processResult(getRc(), getPath(), getStat() == null ? null : new MetaClientInterface.Stat( ZkMetaClientUtil.convertZkEntryModeToMetaClientEntryMode(getStat().getEphemeralOwner()), getStat().getVersion())); } }
9,249
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/ChildListenerAdapter.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import org.apache.helix.metaclient.api.ChildChangeListener; import org.apache.helix.zookeeper.zkclient.IZkChildListener; import org.apache.helix.zookeeper.zkclient.RecursivePersistListener; import org.apache.zookeeper.Watcher; /** * A adapter class to transform {@link ChildChangeListener} to {@link IZkChildListener}. */ public class ChildListenerAdapter implements RecursivePersistListener { private final ChildChangeListener _listener; public ChildListenerAdapter(ChildChangeListener listener) { _listener = listener; } private static ChildChangeListener.ChangeType convertType(Watcher.Event.EventType eventType) { switch (eventType) { case NodeCreated: return ChildChangeListener.ChangeType.ENTRY_CREATED; case NodeDataChanged: return ChildChangeListener.ChangeType.ENTRY_DATA_CHANGE; case NodeDeleted: return ChildChangeListener.ChangeType.ENTRY_DELETED; default: throw new IllegalArgumentException("EventType " + eventType + " is not supported."); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ChildListenerAdapter that = (ChildListenerAdapter) o; return _listener.equals(that._listener); } @Override public int hashCode() { return _listener.hashCode(); } @Override public void handleZNodeChange(String dataPath, Watcher.Event.EventType eventType) throws Exception { _listener.handleChildChange(dataPath, convertType(eventType)); } }
9,250
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/ZkMetaClientExistCallbackHandler.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * 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.metaclient.api.AsyncCallback; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil; import org.apache.helix.zookeeper.zkclient.callback.ZkAsyncCallbacks; /** * Wrapper class for metaclient.api.AsyncCallback. * This wrapper class extends zk callback class. It has an object of user defined * metaclient.api.AsyncCallback. * Each callback will do default retry defined in ZkAsyncCallbacks. (defined in ZkAsyncCallbacks) * * ZkClient execute async callbacks at zkClient main thead, retry is handles in a separate retry * thread. In our first version of implementation, we will keep similar behavior and have * callbacks executed in ZkClient event thread, and reuse zkclient retry logic. */ public class ZkMetaClientExistCallbackHandler extends ZkAsyncCallbacks.ExistsCallbackHandler { AsyncCallback.StatCallback _userCallback; public ZkMetaClientExistCallbackHandler(AsyncCallback.StatCallback cb) { _userCallback = cb; } // Call user passed in callback. Will pass a null for stats if operation fails. @Override public void handle() { _userCallback.processResult(getRc(), getPath(), getStat() == null ? null : new MetaClientInterface.Stat( ZkMetaClientUtil.convertZkEntryModeToMetaClientEntryMode(getStat().getEphemeralOwner()), getStat().getVersion())); } }
9,251
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/StateChangeListenerAdapter.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * 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.metaclient.api.ConnectStateChangeListener; import org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil; import org.apache.helix.zookeeper.zkclient.IZkStateListener; import org.apache.zookeeper.Watcher; public class StateChangeListenerAdapter implements IZkStateListener { private final ConnectStateChangeListener _listener; public StateChangeListenerAdapter(ConnectStateChangeListener listener) { _listener = listener; } @Override public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception { throw new UnsupportedOperationException(); } @Override public void handleNewSession(String sessionId) throws Exception { // This function will be invoked when connection is established. It is a no-op for metaclient. // MetaClient will expose this to user as 'handleStateChanged' already covers state change // notification for new connection establishment. } @Override public void handleSessionEstablishmentError(Throwable error) throws Exception { _listener.handleConnectionEstablishmentError(error); } @Override public void handleStateChanged(Watcher.Event.KeeperState prevState, Watcher.Event.KeeperState curState) throws Exception { _listener.handleConnectStateChanged( ZkMetaClientUtil.translateKeeperStateToMetaClientConnectState(prevState), ZkMetaClientUtil.translateKeeperStateToMetaClientConnectState(curState)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StateChangeListenerAdapter that = (StateChangeListenerAdapter) o; return _listener.equals(that._listener); } @Override public int hashCode() { return _listener.hashCode(); } }
9,252
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/DataListenerAdapter.java
package org.apache.helix.metaclient.impl.zk.adapter; /* * 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.metaclient.api.DataChangeListener; import org.apache.helix.zookeeper.zkclient.IZkDataListener; import org.apache.helix.zookeeper.zkclient.annotation.PreFetchChangedData; import org.apache.zookeeper.Watcher; /** * A Adapter class to transform {@link DataChangeListener} to {@link IZkDataListener} */ public class DataListenerAdapter implements IZkDataListener { private final DataChangeListener _listener; public DataListenerAdapter(DataChangeListener listener) { _listener = listener; } @Override public void handleDataChange(String dataPath, Object data) throws Exception { throw new UnsupportedOperationException("handleDataChange(String dataPath, Object data) is not supported."); } @Override public void handleDataDeleted(String dataPath) throws Exception { handleDataChange(dataPath, null, Watcher.Event.EventType.NodeDeleted); } @Override public void handleDataChange(String dataPath, Object data, Watcher.Event.EventType eventType) throws Exception { _listener.handleDataChange(dataPath, data, convertType(eventType)); } private static DataChangeListener.ChangeType convertType(Watcher.Event.EventType eventType) { switch (eventType) { case NodeCreated: return DataChangeListener.ChangeType.ENTRY_CREATED; case NodeDataChanged: return DataChangeListener.ChangeType.ENTRY_UPDATE; case NodeDeleted: return DataChangeListener.ChangeType.ENTRY_DELETED; default: throw new IllegalArgumentException("EventType " + eventType + " is not supported."); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DataListenerAdapter that = (DataListenerAdapter) o; return _listener.equals(that._listener); } @Override public int hashCode() { return _listener.hashCode(); } }
9,253
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/factory/ZkMetaClientConfig.java
package org.apache.helix.metaclient.impl.zk.factory; /* * 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.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.policy.MetaClientReconnectPolicy; import org.apache.helix.zookeeper.zkclient.serialize.BasicZkSerializer; import org.apache.helix.zookeeper.zkclient.serialize.PathBasedZkSerializer; import org.apache.helix.zookeeper.zkclient.serialize.SerializableSerializer; import org.apache.helix.zookeeper.zkclient.serialize.ZkSerializer; public class ZkMetaClientConfig extends MetaClientConfig { protected final PathBasedZkSerializer _zkSerializer; // Monitoring related fields. MBean names are crated using following variables in format of // MonitorPrefix_monitorType_monitorKey_monitorInstanceName, where _monitorInstanceName is optional // TODO: right now all zkClient mBean object has prefix `HelixZkClient` had coded. We should change // it to a configurable name. protected final String _monitorType; protected final String _monitorKey; protected final String _monitorInstanceName; protected final boolean _monitorRootPathOnly; public PathBasedZkSerializer getZkSerializer() { return _zkSerializer; } public String getMonitorType() { return _monitorType; } public String getMonitorKey() { return _monitorKey; } public String getMonitorInstanceName() { return _monitorInstanceName; } public boolean getMonitorRootPathOnly() { return _monitorRootPathOnly; } protected ZkMetaClientConfig(String connectionAddress, long connectionInitTimeoutInMillis, long sessionTimeoutInMillis, MetaClientReconnectPolicy reconnectPolicy, boolean enableAuth, StoreType storeType, String monitorType, String monitorKey, String monitorInstanceName, boolean monitorRootPathOnly, PathBasedZkSerializer zkSerializer) { super(connectionAddress, connectionInitTimeoutInMillis, sessionTimeoutInMillis, reconnectPolicy, enableAuth, storeType); _zkSerializer = zkSerializer; _monitorType = monitorType; _monitorKey = monitorKey; _monitorInstanceName = monitorInstanceName; _monitorRootPathOnly = monitorRootPathOnly; } public static class ZkMetaClientConfigBuilder extends MetaClientConfig.MetaClientConfigBuilder<ZkMetaClientConfigBuilder> { protected PathBasedZkSerializer _zkSerializer; // Monitoring // Type as in MBean object protected String _monitorType; protected String _monitorKey; protected String _monitorInstanceName = null; protected boolean _monitorRootPathOnly = true; public ZkMetaClientConfigBuilder setZkSerializer( org.apache.helix.zookeeper.zkclient.serialize.PathBasedZkSerializer zkSerializer) { this._zkSerializer = zkSerializer; return this; } public ZkMetaClientConfigBuilder setZkSerializer(ZkSerializer zkSerializer) { this._zkSerializer = new BasicZkSerializer(zkSerializer); return this; } /** * Used as part of the MBean ObjectName. This item is required for enabling monitoring. * @param monitorType */ public ZkMetaClientConfigBuilder setMonitorType(String monitorType) { this._monitorType = monitorType; return this; } /** * Used as part of the MBean ObjectName. This item is required for enabling monitoring. * @param monitorKey */ public ZkMetaClientConfigBuilder setMonitorKey(String monitorKey) { this._monitorKey = monitorKey; return this; } /** * Used as part of the MBean ObjectName. This item is optional. * @param instanceName */ public ZkMetaClientConfigBuilder setMonitorInstanceName(String instanceName) { this._monitorInstanceName = instanceName; return this; } public ZkMetaClientConfigBuilder setMonitorRootPathOnly(Boolean monitorRootPathOnly) { this._monitorRootPathOnly = monitorRootPathOnly; return this; } @Override public ZkMetaClientConfig build() { validate(); return new ZkMetaClientConfig(_connectionAddress, _connectionInitTimeoutInMillis, _sessionTimeoutInMillis, _metaClientReconnectPolicy, _enableAuth, MetaClientConfig.StoreType.ZOOKEEPER, _monitorType, _monitorKey, _monitorInstanceName, _monitorRootPathOnly, _zkSerializer); } @Override protected void validate() { super.validate(); if (_zkSerializer == null) { _zkSerializer = new BasicZkSerializer(new SerializableSerializer()); } } } }
9,254
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/factory/ZkMetaClientFactory.java
package org.apache.helix.metaclient.impl.zk.factory; /* * 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.metaclient.api.MetaClientCacheInterface; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.factories.MetaClientCacheConfig; import org.apache.helix.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.factories.MetaClientFactory; import org.apache.helix.metaclient.impl.zk.ZkMetaClient; import org.apache.helix.metaclient.impl.zk.ZkMetaClientCache; public class ZkMetaClientFactory extends MetaClientFactory { @Override public MetaClientInterface getMetaClient(MetaClientConfig config) { if (config == null) { throw new IllegalArgumentException("MetaClientConfig cannot be null."); } if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType()) && config instanceof ZkMetaClientConfig) { return new ZkMetaClient((ZkMetaClientConfig) config); } throw new IllegalArgumentException("Invalid MetaClientConfig type."); } @Override public MetaClientCacheInterface getMetaClientCache(MetaClientConfig config, MetaClientCacheConfig cacheConfig) { if (config == null) { throw new IllegalArgumentException("MetaClientConfig cannot be null."); } if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType()) && config instanceof ZkMetaClientConfig) { return new ZkMetaClientCache((ZkMetaClientConfig) config, cacheConfig); } throw new IllegalArgumentException("Invalid MetaClientConfig type."); } }
9,255
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/constants/MetaClientConstants.java
package org.apache.helix.metaclient.constants; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public final class MetaClientConstants { private MetaClientConstants(){ } // Stop retrying when we reach timeout //TODO The value should be the same as Helix default ZK retry time. Modify when change #2293 merged public static final int DEFAULT_OPERATION_RETRY_TIMEOUT_MS = Integer.MAX_VALUE; // maxMsToWaitUntilConnected public static final int DEFAULT_CONNECTION_INIT_TIMEOUT_MS = 60 * 1000; // When a client becomes partitioned from the metadata service for more than session timeout, // new session will be established. public static final int DEFAULT_SESSION_TIMEOUT_MS = 30 * 1000; // Max backoff window for exponential reconnect back off policy. by default is 30 seconds. public static final long DEFAULT_MAX_EXP_BACKOFF_RETRY_INTERVAL_MS = 30 * 1000; // Initial backoff window for exponential reconnect back off policy. by default is 500 ms. public static final long DEFAULT_INIT_EXP_BACKOFF_RETRY_INTERVAL_MS = 500; // Auto Reconnect timeout public static final long DEFAULT_AUTO_RECONNECT_TIMEOUT_MS = 30 * 60 * 1000; //public static final long DEFAULT_MAX_LINEAR_BACKOFF_RETRY_WINDOW_MS = 5*1000; }
9,256
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/Permit.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.fasterxml.jackson.databind.annotation.JsonSerialize; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.datamodel.DataRecord; import java.util.concurrent.locks.Lock; @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class Permit extends DataRecord { private static final String DEFAULT_PERMIT_INFO = "permitInfo"; public static final long DEFAULT_TIME_PERMIT_ACQUIRED = -1L; public static final long DEFAULT_TIME_SEMAPHORE_CREATED = -1L; private boolean _isReleased; public enum PermitAttribute { TIME_PERMIT_ACQUIRED, TIME_SEMAPHORE_CREATED } public Permit() { super(DEFAULT_PERMIT_INFO); setPermitFields(DEFAULT_TIME_PERMIT_ACQUIRED, DEFAULT_TIME_SEMAPHORE_CREATED); } public Permit(DataRecord record) { this(); if (record != null) { long timePermitAcquired = record.getLongField(PermitAttribute.TIME_PERMIT_ACQUIRED.name(), DEFAULT_TIME_PERMIT_ACQUIRED); long timeSemaphoreCreated = record.getLongField(PermitAttribute.TIME_SEMAPHORE_CREATED.name(), DEFAULT_TIME_SEMAPHORE_CREATED); setPermitFields(timePermitAcquired, timeSemaphoreCreated); } } public Permit(DataRecord record, MetaClientInterface.Stat stat) { this(record); setTimeSemaphoreCreated(stat.getCreationTime()); setTimePermitAcquired(stat.getModifiedTime()); } public void setPermitFields(long timePermitAcquired, long timeSemaphoreCreated) { setTimePermitAcquired(timePermitAcquired); setTimeSemaphoreCreated(timeSemaphoreCreated); _isReleased = false; } public void setTimePermitAcquired(long timePermitAcquired) { setLongField(PermitAttribute.TIME_PERMIT_ACQUIRED.name(), timePermitAcquired); } public void setTimeSemaphoreCreated(long timeSemaphoreCreated) { setLongField(PermitAttribute.TIME_SEMAPHORE_CREATED.name(), timeSemaphoreCreated); } public void getTimePermitAcquired() { getLongField(PermitAttribute.TIME_PERMIT_ACQUIRED.name(), DEFAULT_TIME_PERMIT_ACQUIRED); } public void getTimeSemaphoreCreated() { getLongField(PermitAttribute.TIME_SEMAPHORE_CREATED.name(), DEFAULT_TIME_SEMAPHORE_CREATED); } public boolean isReleased() { return _isReleased; } public void releasePermit() { _isReleased = true; } }
9,257
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.commons.lang3.NotImplementedException; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.datamodel.DataRecord; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory; import org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.TimeUnit; public class DistributedSemaphore { private final MetaClientInterface<DataRecord> _metaClient; private String _path; private static final String INITIAL_CAPACITY_NAME = "INITIAL_CAPACITY"; private static final String REMAINING_CAPACITY_NAME = "REMAINING_CAPACITY"; private static final long DEFAULT_REMAINING_CAPACITY = -1; private static final Logger LOG = LoggerFactory.getLogger(DistributedSemaphore.class); /** * Create a distributed semaphore client with the given configuration. * @param config configuration of the client */ public DistributedSemaphore(MetaClientConfig config) { if (config == null) { throw new MetaClientException("Configuration cannot be null"); } LOG.info("Creating DistributedSemaphore Client"); if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType())) { ZkMetaClientConfig zkMetaClientConfig = new ZkMetaClientConfig.ZkMetaClientConfigBuilder() .setConnectionAddress(config.getConnectionAddress()) .setZkSerializer(new DataRecordSerializer()) // Currently only support ZNRecordSerializer. // Setting DataRecordSerializer as DataRecord extends ZNRecord. .build(); _metaClient = new ZkMetaClientFactory().getMetaClient(zkMetaClientConfig); _metaClient.connect(); } else { throw new MetaClientException("Unsupported store type: " + config.getStoreType()); } } /** * Connect to an existing distributed semaphore client. * @param client client to connect to */ public DistributedSemaphore(MetaClientInterface<DataRecord> client) { if (client == null) { throw new MetaClientException("Client cannot be null"); } LOG.info("Connecting to existing DistributedSemaphore Client"); _metaClient = client; if (_metaClient.isClosed()) { throw new IllegalStateException("Client already closed!"); } try { _metaClient.connect(); } catch (IllegalStateException e) { // Already connected. } } /** * Create a distributed semaphore with the given path and capacity. * @param path path of the semaphore * @param capacity capacity of the semaphore */ public void createSemaphore(String path, int capacity) { if (capacity <= 0) { throw new MetaClientException("Capacity must be positive"); } if (path == null || path.isEmpty()) { throw new MetaClientException("Invalid path to create semaphore"); } if (_metaClient.exists(path) != null) { throw new MetaClientException("Semaphore already exists"); } if (_metaClient.exists(path) == null) { DataRecord dataRecord = new DataRecord(path); dataRecord.setLongField(INITIAL_CAPACITY_NAME, capacity); dataRecord.setLongField(REMAINING_CAPACITY_NAME, capacity); _metaClient.create(path, dataRecord); _path = path; } } /** * Connect to an existing distributed semaphore. * @param path path of the semaphore */ public void connectSemaphore(String path) { if (path == null || path.isEmpty()) { throw new MetaClientException("Invalid path to connect semaphore"); } if (_metaClient.exists(path) == null) { throw new MetaClientException("Semaphore does not exist"); } _path = path; } /** * Acquire a permit. If no permit is available, log error and return null. * @return a permit */ public Permit acquire() { try { updateAcquirePermit(1); return retrievePermit(_path); } catch (MetaClientException e) { LOG.error("Failed to acquire permit.", e); return null; } } /** * Try to acquire multiple permits. If not enough permits are available, log error and return null. * @param count number of permits to acquire * @return a collection of permits */ public Collection<Permit> acquire(int count) { try { updateAcquirePermit(count); Collection<Permit> permits = new ArrayList<>(); for (int i = 0; i < count; i++) { permits.add(retrievePermit(_path)); } return permits; } catch (MetaClientException e) { LOG.error("Failed to acquire permits.", e); return null; } } /** * Try to acquire a permit. If no enough permit is available, wait for a specific time or return when it was able to acquire. * If timeout <=0, then return immediately when not able to acquire. * @param count number of permits to acquire * @param timeout time to wait * @param unit time unit * @return a collection of permits */ public Collection<Permit> acquire(int count, long timeout, TimeUnit unit) { throw new NotImplementedException("Not implemented yet."); } /** * Get the remaining capacity of the semaphore * @return remaining capacity */ public long getRemainingCapacity() { return getSemaphore().getLongField(REMAINING_CAPACITY_NAME, DEFAULT_REMAINING_CAPACITY); } /** * Get the semaphore data record * @return semaphore data record */ private DataRecord getSemaphore() { if (_metaClient.exists(_path) == null) { throw new MetaClientException("Semaphore does not exist at path: " + _path + ". Please create it first."); } return new DataRecord(_metaClient.get(_path)); } /** * Return a permit. If the permit is already returned, log and return void. */ public void returnPermit(Permit permit) { if (permit.isReleased()) { LOG.info("The permit has already been released"); } else { updateReturnPermit(); permit.releasePermit(); } } /** * Return a collection of permits. If a permit in that collection is already returned, * log and return void. */ public void returnAllPermits(Collection<Permit> permits) { for (Permit permit : permits) { returnPermit(permit); } } /** * Retrieve a permit from the semaphore data record. * @param path path of the permit * @return a permit */ private Permit retrievePermit(String path) { MetaClientInterface.Stat stat = _metaClient.exists(path); return new Permit(getSemaphore(), stat); } /** * Update the remaining capacity of the semaphore after acquiring a permit. * @param count number of permits to acquire */ private void updateAcquirePermit(int count) { _metaClient.update(_path, record -> { long permitsAvailable = record.getLongField(REMAINING_CAPACITY_NAME, DEFAULT_REMAINING_CAPACITY); if (permitsAvailable < count) { throw new MetaClientException("No sufficient permits available. Attempt to acquire " + count + " permits, but only " + permitsAvailable + " permits available"); } record.setLongField(REMAINING_CAPACITY_NAME, permitsAvailable - count); return record; }); } /** * Update the remaining capacity of the semaphore after returning a permit. */ private void updateReturnPermit() { _metaClient.update(_path, record -> { long permitsAvailable = record.getLongField(REMAINING_CAPACITY_NAME, DEFAULT_REMAINING_CAPACITY); record.setLongField(REMAINING_CAPACITY_NAME, permitsAvailable + 1); return record; }); } }
9,258
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClientInterface.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.metaclient.api.MetaClientInterface; public interface LockClientInterface { /** * Acquires a lock at key. * @param key key to identify the entry * @param info Metadata of the lock * @param mode EntryMode identifying if the entry will be deleted upon client disconnect * (Persistent, Ephemeral, or Container) */ void acquireLock(String key, LockInfo info, MetaClientInterface.EntryMode mode); /** * Acquires a lock at key with a TTL. The lock will be deleted after the TTL. * @param key key to identify the entry * @param info Metadata of the lock * @param ttl Time to live in milliseconds */ void acquireLockWithTTL(String key, LockInfo info, long ttl); /** * Renews lock for a TTL Node. * Will fail if key is an invalid path or isn't of type TTL. * @param key key to identify the entry */ void renewTTLLock(String key); /** * Releases the lock. * Will fail if key is an invalid path. * @param key key to identify the entry */ void releaseLock(String key); /** * Obtains the metadata of a lock (the LockInfo). * @param key key to identify the entry * @return LockInfo object of the node at key. If fails to retrieve, return null. * If other error, will raise exception. */ LockInfo retrieveLock(String key); }
9,259
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfoSerializer.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.metaclient.datamodel.DataRecord; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LockInfoSerializer extends ZNRecordSerializer { private static final Logger LOG = LoggerFactory.getLogger(LockInfoSerializer.class); @Override public Object deserialize(byte[] bytes) { try { return new LockInfo(new DataRecord((ZNRecord) super.deserialize(bytes))); } catch (Exception e) { LOG.error("Exception during deserialization of bytes: {}", new String(bytes), e); return null; } } }
9,260
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.metaclient.datamodel.DataRecord; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; public class DataRecordSerializer extends ZNRecordSerializer { @Override public Object deserialize(byte[] bytes) { return new DataRecord((ZNRecord) super.deserialize(bytes)); } }
9,261
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfo.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.fasterxml.jackson.databind.annotation.JsonSerialize; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.datamodel.DataRecord; /** * This structure represents a Lock node information, implemented using DataRecord */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class LockInfo extends DataRecord { // Default values for each attribute if there are no current values set by user public static final String DEFAULT_LOCK_ID_TEXT = ""; public static final String DEFAULT_OWNER_ID_TEXT = ""; public static final String DEFAULT_CLIENT_ID_TEXT = ""; public static final String DEFAULT_CLIENT_DATA = ""; public static final long DEFAULT_GRANTED_AT_LONG = -1L; public static final long DEFAULT_LAST_RENEWED_AT_LONG = -1L; public static final long DEFAULT_TIMEOUT_DURATION = -1L; private static final String DEFAULT_LOCK_INFO = "lockInfo."; /** * The keys to lock information */ public enum LockInfoAttribute { LOCK_ID, OWNER_ID, CLIENT_ID, CLIENT_DATA, GRANTED_AT, LAST_RENEWED_AT, TIMEOUT } /** * Initialize a default LockInfo instance */ public LockInfo() { super(DEFAULT_LOCK_INFO); setLockInfoFields(DEFAULT_LOCK_ID_TEXT, DEFAULT_OWNER_ID_TEXT, DEFAULT_CLIENT_ID_TEXT, DEFAULT_CLIENT_DATA, DEFAULT_GRANTED_AT_LONG, DEFAULT_LAST_RENEWED_AT_LONG, DEFAULT_TIMEOUT_DURATION); } /** * Initialize a LockInfo with a DataRecord, set all info fields to default data * @param dataRecord The dataRecord contains lock node data that used to initialize the LockInfo */ public LockInfo(DataRecord dataRecord) { this(); if (dataRecord != null) { String lockId = dataRecord.getSimpleField(LockInfoAttribute.LOCK_ID.name()); String ownerId = dataRecord.getSimpleField(LockInfoAttribute.OWNER_ID.name()); String clientId = dataRecord.getSimpleField(LockInfoAttribute.CLIENT_ID.name()); String clientData = dataRecord.getSimpleField(LockInfoAttribute.CLIENT_DATA.name()); long grantTime = dataRecord.getLongField(LockInfoAttribute.GRANTED_AT.name(), DEFAULT_GRANTED_AT_LONG); long lastRenewalTime = dataRecord.getLongField(LockInfoAttribute.LAST_RENEWED_AT.name(), DEFAULT_LAST_RENEWED_AT_LONG); long timeout = dataRecord.getLongField(LockInfoAttribute.TIMEOUT.name(), DEFAULT_TIMEOUT_DURATION); setLockInfoFields(lockId,ownerId, clientId, clientData, grantTime, lastRenewalTime, timeout); } } /** * Initialize a LockInfo with a DataRecord and a Stat, set all info fields to default data * @param dataRecord The dataRecord contains lock node data that used to initialize the LockInfo * @param stat The stat of the lock node */ public LockInfo(DataRecord dataRecord, MetaClientInterface.Stat stat) { this(dataRecord); //Synchronize the lockInfo with the stat setGrantedAt(stat.getCreationTime()); setLastRenewedAt(stat.getModifiedTime()); } /** * Initialize a LockInfo with data for each field, set all null info fields to default data * @param lockId value of LOCK_ID attribute * @param ownerId value of OWNER_ID attribute * @param clientId value of CLIENT_ID attribute * @param clientData value of CLIENT_DATA attribute * @param grantTime the time the lock was granted * @param lastRenewalTime the last time the lock was renewed * @param timeout value of TIMEOUT attribute */ public LockInfo(String lockId, String ownerId, String clientId, String clientData, long grantTime, long lastRenewalTime, long timeout) { this(); setLockInfoFields(lockId, ownerId, clientId, clientData, grantTime, lastRenewalTime, timeout); } /** * Set each field of lock info to user provided values if the values * are not null, null values are set to default values * @param lockId value of LOCK_ID attribute * @param ownerId value of OWNER_ID attribute * @param clientId value of CLIENT_ID attribute * @param clientData value of CLIENT_DATA attribute * @param grantTime the time the lock was granted * @param lastRenewalTime the last time the lock was renewed * @param timeout value of TIMEOUT attribute */ private void setLockInfoFields(String lockId, String ownerId, String clientId, String clientData, long grantTime, long lastRenewalTime, long timeout) { setLockId(lockId); setOwnerId(ownerId); setClientId(clientId); setClientData(clientData); setGrantedAt(grantTime); setLastRenewedAt(lastRenewalTime); setTimeout(timeout); } /** * Set the value for LOCK_ID attribute of the lock * @param lockId Is a unique identifier representing the lock. * It is created by the lockClient and a new one is created for each time the lock is acquired. */ public void setLockId(String lockId) { setSimpleField(LockInfoAttribute.LOCK_ID.name(), lockId == null ? DEFAULT_LOCK_ID_TEXT : lockId); } /** * Get the value for OWNER_ID attribute of the lock * @param ownerId Represents the initiator of the lock, created by the client. * A service can have multiple ownerId's as long as acquire and release are called * by the same owner. */ public void setOwnerId(String ownerId) { setSimpleField(LockInfoAttribute.OWNER_ID.name(), ownerId == null ? DEFAULT_OWNER_ID_TEXT : ownerId); } /** * Get the value for CLIENT_ID attribute of the lock * @param clientId Unique identifier that represents who will get the lock (the client). */ public void setClientId(String clientId) { setSimpleField(LockInfoAttribute.CLIENT_ID.name(), clientId == null ? DEFAULT_CLIENT_ID_TEXT : clientId); } /** * Get the value for CLIENT_DATA attribute of the lock * @param clientData String representing the serialized data object */ public void setClientData(String clientData) { setSimpleField(LockInfoAttribute.CLIENT_DATA.name(), clientData == null ? DEFAULT_CLIENT_DATA : clientData); } /** * Get the value for GRANTED_AT attribute of the lock * @param grantTime Long representing the time at which the lock was granted */ public void setGrantedAt(Long grantTime) { setLongField(LockInfoAttribute.GRANTED_AT.name(), grantTime); } /** * Get the value for LAST_RENEWED_AT attribute of the lock * @param lastRenewalTime Long representing the time at which the lock was last renewed */ public void setLastRenewedAt(Long lastRenewalTime) { setLongField(LockInfoAttribute.LAST_RENEWED_AT.name(), lastRenewalTime); } /** * Get the value for TIMEOUT attribute of the lock * @param timeout Long representing the duration of a lock in milliseconds. */ public void setTimeout(long timeout) { // Always store the timeout value in milliseconds for the sake of simplicity setLongField(LockInfoAttribute.TIMEOUT.name(), timeout); } /** * Get the value for OWNER_ID attribute of the lock * @return the owner id of the lock, {@link #DEFAULT_OWNER_ID_TEXT} if there is no owner id set */ public String getOwnerId() { return getStringField(LockInfoAttribute.OWNER_ID.name(), DEFAULT_OWNER_ID_TEXT); } /** * Get the value for CLIENT_ID attribute of the lock * @return the client id of the lock, {@link #DEFAULT_CLIENT_ID_TEXT} if there is no client id set */ public String getClientId() { return getStringField(LockInfoAttribute.CLIENT_ID.name(), DEFAULT_CLIENT_ID_TEXT); } /** * Get the value for LOCK_ID attribute of the lock * @return the id of the lock, {@link #DEFAULT_LOCK_ID_TEXT} if there is no lock id set */ public String getLockId() { return getStringField(LockInfoAttribute.LOCK_ID.name(), DEFAULT_LOCK_ID_TEXT); } /** * Get value of CLIENT_DATA * @return the string representing the serialized client data, {@link #DEFAULT_CLIENT_DATA} * if there is no client data set. */ public String getClientData() { return getStringField(LockInfoAttribute.CLIENT_DATA.name(), DEFAULT_CLIENT_DATA); } /** * Get the time the lock was granted on * @return the grant time of the lock, {@link #DEFAULT_GRANTED_AT_LONG} * if there is no grant time set */ public Long getGrantedAt() { return getLongField(LockInfoAttribute.GRANTED_AT.name(), DEFAULT_GRANTED_AT_LONG); } /** * Get the last time the lock was renewed * @return the last renewal time of the lock, {@link #DEFAULT_LAST_RENEWED_AT_LONG} * if there is no renewal time set */ public Long getLastRenewedAt() { return getLongField(LockInfoAttribute.LAST_RENEWED_AT.name(), DEFAULT_LAST_RENEWED_AT_LONG); } /** * Get the value for TIMEOUT attribute of the lock * @return the expiring time of the lock, {@link #DEFAULT_TIMEOUT_DURATION} if there is no timeout set */ public long getTimeout() { return getLongField(LockInfoAttribute.TIMEOUT.name(), DEFAULT_TIMEOUT_DURATION); } }
9,262
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
package org.apache.helix.metaclient.recipes.lock; /* * 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.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.api.Op; import org.apache.helix.metaclient.datamodel.DataRecord; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; public class LockClient implements LockClientInterface, AutoCloseable { private final MetaClientInterface<LockInfo> _metaClient; //NEW_METACLIENT is used to indicate whether the metaClient is created by the LockClient or not. private static Boolean NEW_METACLIENT = false; private static final Logger LOG = LoggerFactory.getLogger(LockClient.class); public LockClient(MetaClientConfig config) { if (config == null) { throw new IllegalArgumentException("MetaClientConfig cannot be null."); } LOG.info("Creating MetaClient for LockClient"); if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType())) { ZkMetaClientConfig zkMetaClientConfig = new ZkMetaClientConfig.ZkMetaClientConfigBuilder(). setConnectionAddress(config.getConnectionAddress()) .setZkSerializer((new LockInfoSerializer())) .build(); _metaClient = new ZkMetaClientFactory().getMetaClient(zkMetaClientConfig); _metaClient.connect(); NEW_METACLIENT = true; } else { throw new MetaClientException("Unsupported store type: " + config.getStoreType()); } } public LockClient(MetaClientInterface<LockInfo> client) { if (client == null) { throw new IllegalArgumentException("MetaClient cannot be null."); } _metaClient = client; if (_metaClient.isClosed()) { throw new IllegalStateException("Client already closed!"); } try { _metaClient.connect(); } catch (IllegalStateException e) { // Already connected. } } @Override public void acquireLock(String key, LockInfo lockInfo, MetaClientInterface.EntryMode mode) { _metaClient.create(key, lockInfo, mode); } @Override public void acquireLockWithTTL(String key, LockInfo lockInfo, long ttl) { _metaClient.createWithTTL(key, lockInfo, ttl); } @Override public void renewTTLLock(String key) { _metaClient.renewTTLNode(key); } @Override public void releaseLock(String key) { MetaClientInterface.Stat stat = _metaClient.exists(key); if (stat != null) { int version = stat.getVersion(); List<Op> ops = Arrays.asList( Op.check(key, version), Op.delete(key, version)); _metaClient.transactionOP(ops); if (_metaClient.exists(key) != null) { throw new MetaClientException("Failed to release lock for key: " + key); } } } @Override public LockInfo retrieveLock(String key) { MetaClientInterface.Stat stat = _metaClient.exists(key); if (stat == null) { return null; } return new LockInfo(_metaClient.get(key), stat); } @Override public void close() { if (NEW_METACLIENT) { LOG.info("Closing created MetaClient for LockClient"); } else { LOG.warn("Closing existing MetaClient"); } _metaClient.disconnect(); } }
9,263
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java
package org.apache.helix.metaclient.recipes.leaderelection; import org.apache.helix.metaclient.api.ConnectStateChangeListener; import org.apache.helix.metaclient.api.DataChangeListener; import org.apache.helix.metaclient.api.MetaClientInterface; import static org.apache.helix.metaclient.recipes.leaderelection.LeaderElectionListenerInterface.ChangeType.*; public class LeaderElectionListenerInterfaceAdapter implements DataChangeListener, ConnectStateChangeListener { private String _leaderPath; private final LeaderElectionListenerInterface _leaderElectionListener; public LeaderElectionListenerInterfaceAdapter(String leaderPath, LeaderElectionListenerInterface leaderElectionListener) { _leaderPath = leaderPath; _leaderElectionListener = leaderElectionListener; } @Override public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception { switch (changeType) { case ENTRY_CREATED: case ENTRY_UPDATE: String newLeader = ((LeaderInfo) data).getLeaderName(); _leaderElectionListener.onLeadershipChange(_leaderPath, LEADER_ACQUIRED, newLeader); break; case ENTRY_DELETED: _leaderElectionListener.onLeadershipChange(_leaderPath, LEADER_LOST, ""); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LeaderElectionListenerInterfaceAdapter that = (LeaderElectionListenerInterfaceAdapter) o; return _leaderElectionListener.equals(that._leaderElectionListener); } @Override public int hashCode() { return _leaderElectionListener.hashCode(); } @Override public void handleConnectStateChanged(MetaClientInterface.ConnectState prevState, MetaClientInterface.ConnectState currentState) throws Exception { if (currentState == MetaClientInterface.ConnectState.DISCONNECTED) { // when disconnected, notify leader lost even though the ephmeral node is not gone until expire // Leader election client will touch the node if reconnect before expire _leaderElectionListener.onLeadershipChange(_leaderPath, LEADER_LOST, ""); } } @Override public void handleConnectionEstablishmentError(Throwable error) throws Exception { } }
9,264
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
package org.apache.helix.metaclient.recipes.leaderelection; /* * 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.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.helix.metaclient.api.ConnectStateChangeListener; import org.apache.helix.metaclient.api.DataChangeListener; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.api.Op; import org.apache.helix.metaclient.api.OpResult; import org.apache.helix.metaclient.exception.MetaClientBadVersionException; import org.apache.helix.metaclient.exception.MetaClientException; import org.apache.helix.metaclient.exception.MetaClientNoNodeException; import org.apache.helix.metaclient.exception.MetaClientNodeExistsException; import org.apache.helix.metaclient.factories.MetaClientConfig; import org.apache.helix.metaclient.impl.zk.ZkMetaClient; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.helix.metaclient.api.OpResult.Type.*; /** * LeaderElectionClient does distributed leader election using CRUD and change notification APIs * provided by underlying metadata client. Leader election config can provide many * configs like base path for all participating nodes, sync/async mode, TTL etc. * * Participants join a leader election group by calling the following API. * The Leader Election client maintains and elect an active leader from participant pool. * All participants wanted to be elected as leader joins a pool. * LeaderElection client maintains an active leader, by monitoring liveness of current leader and * re-elect if needed and user no need to call elect or re-elect explicitly. * This LeaderElection client will notify registered listeners for any leadership change. * * One client is created per each participant(host). One participant can join multiple leader * election groups using the same client. * When the client is used by a leader election service, one client is created for each participant. * */ public class LeaderElectionClient implements AutoCloseable { private final MetaClientInterface<LeaderInfo> _metaClient; private final String _participant; private static final Logger LOG = LoggerFactory.getLogger(LeaderElectionClient.class); // A list of leader election group that this client joins. private Set<String> _leaderGroups = new HashSet<>(); private Map<String, LeaderInfo> _participantInfos = new HashMap<>(); private final static String LEADER_ENTRY_KEY = "/LEADER"; private final static String PARTICIPANTS_ENTRY_KEY = "/PARTICIPANTS"; private final static String PARTICIPANTS_ENTRY_PARENT = "/PARTICIPANTS/"; ReElectListener _reElectListener = new ReElectListener(); ConnectStateListener _connectStateListener = new ConnectStateListener(); /** * Construct a LeaderElectionClient using a user passed in leaderElectionConfig. It creates a MetaClient * instance underneath. * When MetaClient is auto closed because of being disconnected and auto retry connection timed out, A new * MetaClient instance will be created and keeps retry connection. * * @param metaClientConfig The config used to create an metaclient. */ public LeaderElectionClient(MetaClientConfig metaClientConfig, String participant) { _participant = participant; if (metaClientConfig == null) { throw new IllegalArgumentException("MetaClientConfig cannot be null."); } LOG.info("Creating MetaClient for LeaderElectionClient"); if (MetaClientConfig.StoreType.ZOOKEEPER.equals(metaClientConfig.getStoreType())) { ZkMetaClientConfig zkMetaClientConfig = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress( metaClientConfig.getConnectionAddress()).setZkSerializer((new LeaderInfoSerializer())).build(); _metaClient = new ZkMetaClientFactory().getMetaClient(zkMetaClientConfig); _metaClient.connect(); _metaClient.subscribeStateChanges(_connectStateListener); } else { throw new MetaClientException("Unsupported store type: " + metaClientConfig.getStoreType()); } } /** * Construct a LeaderElectionClient using a user passed in MetaClient object * When MetaClient is auto closed because of being disconnected and auto retry connection timed out, user * will need to create a new MetaClient and a new LeaderElectionClient instance. * * @param metaClient metaClient object to be used. */ public LeaderElectionClient(MetaClientInterface<LeaderInfo> metaClient, String participant) { throw new UnsupportedOperationException("Not supported yet."); } /** * Returns true if current participant is the current leadership. */ public boolean isLeader(String leaderPath) { return getLeader(leaderPath).equalsIgnoreCase(_participant); } /** * Participants join a leader election group by calling the following API. * The Leader Election client maintains and elect an active leader from the participant pool. * * @param leaderPath The path for leader election. * @throws RuntimeException if the operation is not succeeded. */ public void joinLeaderElectionParticipantPool(String leaderPath) { subscribeAndTryCreateLeaderEntry(leaderPath); createParticipantInfo(leaderPath, new LeaderInfo(_participant)); } /** * Participants join a leader election group by calling the following API. * The Leader Election client maintains and elect an active leader from the participant pool. * * @param leaderPath The path for leader election. * @param userInfo Any additional information to associate with this participant. * @throws RuntimeException if the operation is not succeeded. */ public void joinLeaderElectionParticipantPool(String leaderPath, LeaderInfo userInfo) { subscribeAndTryCreateLeaderEntry(leaderPath); LeaderInfo participantInfo = new LeaderInfo(userInfo); createParticipantInfo(leaderPath, participantInfo); } private void createParticipantInfo(String leaderPath, LeaderInfo participantInfo) { _participantInfos.put(leaderPath, participantInfo); createPathIfNotExists(leaderPath + PARTICIPANTS_ENTRY_KEY); try { // try to create participant info entry, assuming leader election group node is already there _metaClient.create(leaderPath + PARTICIPANTS_ENTRY_PARENT + _participant, participantInfo, MetaClientInterface.EntryMode.EPHEMERAL); } catch (MetaClientNodeExistsException ex) { throw new ConcurrentModificationException("Already joined leader election group. ", ex); } catch (MetaClientNoNodeException ex) { // Leader group root entry or participant parent entry is gone after we checked or created. // Meaning other client removed the group. Throw ConcurrentModificationException. throw new ConcurrentModificationException( "Other client trying to modify the leader election group at the same time, please retry.", ex); } } private void createPathIfNotExists(String path) { if (_metaClient.exists(path) == null) { LOG.info("{} Creating leader group directory {}.", _participant, path); try { _metaClient.create(path, null); } catch (MetaClientNodeExistsException ignore) { LOG.info("Leader election group root path already created: path {}.", path); } } } private void subscribeAndTryCreateLeaderEntry(String leaderPath) { _metaClient.subscribeDataChange(leaderPath + LEADER_ENTRY_KEY, _reElectListener, false); LeaderInfo leaderInfo = new LeaderInfo(LEADER_ENTRY_KEY); leaderInfo.setLeaderName(_participant); try { createPathIfNotExists(leaderPath); } catch (MetaClientNoNodeException e) { // Parent entry missed in root path. throw new MetaClientException("Parent entry in leaderGroup path" + leaderPath + " does not exist."); } // create actual leader node try { LOG.info("{} joining leader group {}.", _participant, leaderPath); // try to create leader entry, assuming leader election group node is already there _metaClient.create(leaderPath + LEADER_ENTRY_KEY, leaderInfo, MetaClientInterface.EntryMode.EPHEMERAL); } catch (MetaClientNodeExistsException ex) { LOG.info("Already a leader in leader group {}.", leaderPath); } _leaderGroups.add(leaderPath + LEADER_ENTRY_KEY); } /** * Any participant may exit the exitLeaderElectionParticipantPool by calling the API. * If the participant is not the current leader, it leaves the pool and won't participant future * leader election process. * If the participant is the current leader, it leaves the pool and a new leader will be elected * if there are other participants in the pool. * Throws exception if the participant is not in the pool. * * @param leaderPath The path for leader election. * @throws RuntimeException if the operation is not succeeded. * * @throws RuntimeException If the participant did not join participant pool via this client. */ public void exitLeaderElectionParticipantPool(String leaderPath) { _metaClient.unsubscribeDataChange(leaderPath + LEADER_ENTRY_KEY, _reElectListener); // TODO: remove from pool folder relinquishLeaderHelper(leaderPath, true); } /** * Releases leadership for participant. Still stays in the participant pool. * * @param leaderPath The path for leader election. * * @throws RuntimeException if the leadership is not owned by this participant, or if the * participant did not join participant pool via this client. */ public void relinquishLeader(String leaderPath) { relinquishLeaderHelper(leaderPath, false); } /** * relinquishLeaderHelper and LeaderElectionParticipantPool if configured * @param leaderPath * @param exitLeaderElectionParticipantPool */ private void relinquishLeaderHelper(String leaderPath, Boolean exitLeaderElectionParticipantPool) { String key = leaderPath + LEADER_ENTRY_KEY; // if current client is in the group if (!_leaderGroups.contains(key)) { throw new MetaClientException("Participant is not in the leader election group"); } // remove leader path from leaderGroups after check if exiting the pool. // to prevent a race condition in In Zk implementation: // If there are delays in ZkClient event queue, it is possible the leader election client received leader // deleted event after unsubscribeDataChange. We will need to remove it from in memory `leaderGroups` map before // deleting ZNode. So that handler in ReElectListener won't recreate the leader node. if (exitLeaderElectionParticipantPool) { _leaderGroups.remove(leaderPath + LEADER_ENTRY_KEY); _metaClient.delete(leaderPath + PARTICIPANTS_ENTRY_PARENT + _participant); } // check if current participant is the leader // read data and stats, check, and multi check + delete try { ImmutablePair<LeaderInfo, MetaClientInterface.Stat> tup = _metaClient.getDataAndStat(key); if (tup.left.getLeaderName().equalsIgnoreCase(_participant)) { int expectedVersion = tup.right.getVersion(); List<Op> ops = Arrays.asList(Op.check(key, expectedVersion), Op.delete(key, expectedVersion)); //Execute transactional support on operations List<OpResult> opResults = _metaClient.transactionOP(ops); if (opResults.get(0).getType() == ERRORRESULT) { if (isLeader(leaderPath)) { // Participant re-elected as leader. throw new ConcurrentModificationException("Concurrent operation, please retry"); } else { LOG.info("Someone else is already leader"); } } } } catch (MetaClientNoNodeException ex) { LOG.info("No Leader for participant pool {} when exit the pool", leaderPath); } } /** * Get current leader. * * @param leaderPath The path for leader election. * @return Returns the current leader. Return null if no Leader at a given point. * @throws RuntimeException when leader path does not exist. // TODO: define exp type */ public String getLeader(String leaderPath) { LeaderInfo leaderInfo = _metaClient.get(leaderPath + LEADER_ENTRY_KEY); return leaderInfo == null ? null : leaderInfo.getLeaderName(); } /** * Get current leader. * * @param leaderPath The path for leader election. * @return Returns a LeaderInfo entry. Return null if participant is not in the pool. * */ public LeaderInfo getParticipantInfo(String leaderPath, String participant) { return _metaClient.get(leaderPath + PARTICIPANTS_ENTRY_PARENT + participant); } public MetaClientInterface.Stat getLeaderEntryStat(String leaderPath) { return _metaClient.exists(leaderPath + LEADER_ENTRY_KEY); } /** * Return a list of hosts in participant pool * * @param leaderPath The path for leader election. * @return a list of participant(s) that tried to elect themselves as leader. The current leader * is not included in the list. * Return an empty list if * 1. There is a leader for this path but there is no other participants * 2. There is no leader for this path at the time of query * @throws RuntimeException when leader path does not exist. // TODO: define exp type */ public List<String> getParticipants(String leaderPath) { try { return _metaClient.getDirectChildrenKeys(leaderPath + PARTICIPANTS_ENTRY_KEY); } catch (MetaClientNoNodeException ex) { throw new MetaClientException("No leader election group create for path " + leaderPath, ex); } } /** * APIs to register/unregister listener to leader path. All the participants can listen to any * leaderPath, Including leader going down or a new leader comes up. * Whenever current leader for that leaderPath goes down (considering it's ephemeral entity which * get's auto-deleted after TTL or session timeout) or a new leader comes up, it notifies all * participants who have been listening on entryChange event. * * A listener will still be installed if the path does not exist yet. * * @param leaderPath The path for leader election that listener is interested for change. * @param listener An implementation of LeaderElectionListenerInterface * @return A boolean value indicating if registration is success. */ public boolean subscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) { LeaderElectionListenerInterfaceAdapter adapter = new LeaderElectionListenerInterfaceAdapter(leaderPath, listener); _metaClient.subscribeDataChange(leaderPath + LEADER_ENTRY_KEY, adapter, false /*skipWatchingNonExistNode*/); // we need to subscribe event when path is not there _metaClient.subscribeStateChanges(adapter); return false; } /** * @param leaderPath The path for leader election that listener is no longer interested for change. * @param listener An implementation of LeaderElectionListenerInterface */ public void unsubscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) { LeaderElectionListenerInterfaceAdapter adapter = new LeaderElectionListenerInterfaceAdapter(leaderPath, listener); _metaClient.unsubscribeDataChange(leaderPath + LEADER_ENTRY_KEY, adapter ); _metaClient.unsubscribeConnectStateChanges(adapter); } @Override public void close() throws Exception { _metaClient.unsubscribeConnectStateChanges(_connectStateListener); // exit all previous joined leader election groups for (String leaderGroup : _leaderGroups) { String leaderGroupPathName = leaderGroup.substring(0, leaderGroup.length() - LEADER_ENTRY_KEY.length() /*remove '/LEADER' */); exitLeaderElectionParticipantPool(leaderGroupPathName); } // TODO: if last participant, remove folder _metaClient.disconnect(); } class ReElectListener implements DataChangeListener { @Override public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception { if (changeType == ChangeType.ENTRY_CREATED) { LOG.info("new leader for leader election group {}.", key); } else if (changeType == ChangeType.ENTRY_DELETED) { if (_leaderGroups.contains(key)) { LeaderInfo lf = new LeaderInfo("LEADER"); lf.setLeaderName(_participant); try { LOG.info("Leader gone for group {}, {} try to reelect.", key, _participant); _metaClient.create(key, lf, MetaClientInterface.EntryMode.EPHEMERAL); } catch (MetaClientNodeExistsException ex) { LOG.info("Already a leader for leader election group {}.", key); } } } } } class ConnectStateListener implements ConnectStateChangeListener { @Override public void handleConnectStateChanged(MetaClientInterface.ConnectState prevState, MetaClientInterface.ConnectState currentState) throws Exception { if (prevState == MetaClientInterface.ConnectState.EXPIRED && currentState == MetaClientInterface.ConnectState.CONNECTED) { for (String leaderPath : _participantInfos.keySet()) { _metaClient.create(leaderPath + PARTICIPANTS_ENTRY_PARENT + _participant, _participantInfos.get(leaderPath), MetaClientInterface.EntryMode.EPHEMERAL); } } else if (prevState == MetaClientInterface.ConnectState.DISCONNECTED && currentState == MetaClientInterface.ConnectState.CONNECTED) { touchLeaderNode(); } } @Override public void handleConnectionEstablishmentError(Throwable error) throws Exception { } } private void touchLeaderNode() { for (String leaderPath : _leaderGroups) { String key = leaderPath; ImmutablePair<LeaderInfo, MetaClientInterface.Stat> tup = _metaClient.getDataAndStat(key); if (tup.left.getLeaderName().equalsIgnoreCase(_participant)) { int expectedVersion = tup.right.getVersion(); try { _metaClient.set(key, tup.left, expectedVersion); } catch (MetaClientNoNodeException ex) { LOG.info("leaderPath {} gone when retouch leader node.", key); } catch (MetaClientBadVersionException e) { LOG.info("New leader for leaderPath {} when retouch leader node.", key); } catch (MetaClientException ex) { LOG.warn("Failed to touch {} when reconnected.", key, ex); } } } } public MetaClientInterface getMetaClient() { return _metaClient; } }
9,265
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterface.java
package org.apache.helix.metaclient.recipes.leaderelection; /* * 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. */ /** * It provides APIs for listener listening on events like a new leader is created or current * leader node is deleted. */ public interface LeaderElectionListenerInterface { enum ChangeType { LEADER_ACQUIRED, LEADER_LOST } // When new leader is elected: // ChangeType == NEW_LEADER_ELECTED, curLeader is the new leader name // When no leader anymore: // ChangeType == LEADER_GONE, curLeader is an empty string // In ZK implementation, since notification does not include changed data and metaclient fetches // the entry when event comes, it is possible that public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader); }
9,266
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfoSerializer.java
package org.apache.helix.metaclient.recipes.leaderelection; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import java.io.ByteArrayInputStream; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.apache.helix.zookeeper.util.GZipCompressionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeaderInfoSerializer extends ZNRecordSerializer { private static final Logger LOG = LoggerFactory.getLogger(LeaderInfoSerializer.class); @Override public Object deserialize(byte[] bytes) { if (bytes == null || bytes.length == 0) { // reading a parent/null node return null; } ByteArrayInputStream bais = new ByteArrayInputStream(bytes); mapper.enable(MapperFeature.AUTO_DETECT_FIELDS); mapper.enable(MapperFeature.AUTO_DETECT_SETTERS); mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); try { //decompress the data if its already compressed if (GZipCompressionUtil.isCompressed(bytes)) { byte[] uncompressedBytes = GZipCompressionUtil.uncompress(bais); bais = new ByteArrayInputStream(uncompressedBytes); } return mapper.readValue(bais, LeaderInfo.class); } catch (Exception e) { LOG.error("Exception during deserialization of bytes: {}", new String(bytes), e); return null; } } }
9,267
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfo.java
package org.apache.helix.metaclient.recipes.leaderelection; /* * 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.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.apache.helix.metaclient.datamodel.DataRecord; /** * This is the data represent leader election info of a leader election path. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class LeaderInfo extends DataRecord { public LeaderInfo(DataRecord dataRecord) { super(dataRecord); } @JsonCreator public LeaderInfo(@JsonProperty("id") String id) { super(id); } public LeaderInfo(LeaderInfo info, String id) { super(info, id); } public enum LeaderAttribute { LEADER_NAME, PARTICIPANTS } @JsonIgnore(true) public String getLeaderName() { return getSimpleField("LEADER_NAME"); } @JsonIgnore(true) public void setLeaderName(String id) { setSimpleField("LEADER_NAME", id); } }
9,268
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/factories/MetaClientCacheConfig.java
package org.apache.helix.metaclient.factories; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public class MetaClientCacheConfig { private final String _rootEntry; private final boolean _cacheData; private final boolean _cacheChildren; public MetaClientCacheConfig(String rootEntry, boolean cacheData, boolean cacheChildren) { _rootEntry = rootEntry; _cacheData = cacheData; _cacheChildren = cacheChildren; } public String getRootEntry() { return _rootEntry; } public boolean getCacheData() { return _cacheData; } public boolean getCacheChildren() { return _cacheChildren; } }
9,269
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/factories/MetaClientConfig.java
package org.apache.helix.metaclient.factories; /* * 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.metaclient.constants.MetaClientConstants; import org.apache.helix.metaclient.policy.ExponentialBackoffReconnectPolicy; import org.apache.helix.metaclient.policy.MetaClientReconnectPolicy; public class MetaClientConfig { public enum StoreType { ZOOKEEPER, ETCD, CUSTOMIZED } private final String _connectionAddress; // Wait for init timeout time until connection is initiated private final long _connectionInitTimeoutInMillis; // When a client becomes partitioned from the metadata service for more than session timeout, // new session will be established when reconnect. private final long _sessionTimeoutInMillis; // Policy to define client re-establish connection behavior when the connection to underlying // metadata store is expired. private final MetaClientReconnectPolicy _metaClientReconnectPolicy; private final boolean _enableAuth; private final StoreType _storeType; public String getConnectionAddress() { return _connectionAddress; } public long getConnectionInitTimeoutInMillis() { return _connectionInitTimeoutInMillis; } public boolean isAuthEnabled() { return _enableAuth; } public StoreType getStoreType() { return _storeType; } public long getSessionTimeoutInMillis() { return _sessionTimeoutInMillis; } public MetaClientReconnectPolicy getMetaClientReconnectPolicy() { return _metaClientReconnectPolicy; } // TODO: More options to add later // private boolean _autoReRegistWatcher; // re-register one time watcher when set to true // private boolean _resetWatchWhenReConnect; // re-register previous existing watcher when reconnect protected MetaClientConfig(String connectionAddress, long connectionInitTimeoutInMillis, long sessionTimeoutInMillis, MetaClientReconnectPolicy metaClientReconnectPolicy, boolean enableAuth, StoreType storeType) { _connectionAddress = connectionAddress; _connectionInitTimeoutInMillis = connectionInitTimeoutInMillis; _sessionTimeoutInMillis = sessionTimeoutInMillis; _metaClientReconnectPolicy = metaClientReconnectPolicy; _enableAuth = enableAuth; _storeType = storeType; } public static class MetaClientConfigBuilder<B extends MetaClientConfigBuilder<B>> { protected String _connectionAddress; protected long _connectionInitTimeoutInMillis; protected long _sessionTimeoutInMillis; protected boolean _enableAuth; protected StoreType _storeType; protected MetaClientReconnectPolicy _metaClientReconnectPolicy; public MetaClientConfig build() { validate(); return new MetaClientConfig(_connectionAddress, _connectionInitTimeoutInMillis, _sessionTimeoutInMillis, _metaClientReconnectPolicy, _enableAuth, _storeType); } public MetaClientConfigBuilder() { // set default values setStoreType(StoreType.ZOOKEEPER); setAuthEnabled(false); setConnectionInitTimeoutInMillis(MetaClientConstants.DEFAULT_CONNECTION_INIT_TIMEOUT_MS); setSessionTimeoutInMillis(MetaClientConstants.DEFAULT_SESSION_TIMEOUT_MS); } public B setConnectionAddress(String connectionAddress) { _connectionAddress = connectionAddress; return self(); } public B setAuthEnabled(Boolean enableAuth) { _enableAuth = enableAuth; return self(); } /** * Set timeout in ms for connection initialization timeout * @param timeout * @return */ public B setConnectionInitTimeoutInMillis(long timeout) { _connectionInitTimeoutInMillis = timeout; return self(); } /** * Set reconnect policy when connection is lost or expired. By default is * ExponentialBackoffReconnectPolicy * @param reconnectPolicy an instance of type MetaClientReconnectPolicy * @return */ public B setMetaClientReconnectPolicy(MetaClientReconnectPolicy reconnectPolicy) { _metaClientReconnectPolicy = reconnectPolicy; return self(); } /** * Set timeout in mm for session timeout. When a client becomes partitioned from the metadata * service for more than session timeout, new session will be established. * @param timeout * @return */ public B setSessionTimeoutInMillis(long timeout) { _sessionTimeoutInMillis = timeout; return self(); } public B setStoreType(StoreType storeType) { _storeType = storeType; return self(); } @SuppressWarnings("unchecked") final B self() { return (B) this; } protected void validate() { if (_metaClientReconnectPolicy == null) { _metaClientReconnectPolicy = new ExponentialBackoffReconnectPolicy(); } if (_storeType == null || _connectionAddress == null) { throw new IllegalArgumentException( "MetaClientConfig.Builder: store type or connection string is null"); } } } }
9,270
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/factories/MetaClientFactory.java
package org.apache.helix.metaclient.factories; /* * 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.metaclient.api.MetaClientCacheInterface; import org.apache.helix.metaclient.api.MetaClientInterface; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig; import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A factory class for MetaClient. It returns MetaClient entity based on config. */ public class MetaClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MetaClientFactory.class); public MetaClientInterface getMetaClient(MetaClientConfig config) { if (config == null) { throw new IllegalArgumentException("MetaClientConfig cannot be null."); } if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType())) { return new ZkMetaClientFactory().getMetaClient(createZkMetaClientConfig(config)); } return null; } public MetaClientCacheInterface getMetaClientCache(MetaClientConfig config, MetaClientCacheConfig cacheConfig) { if (config == null) { throw new IllegalArgumentException("MetaClientConfig cannot be null."); } if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType())) { return new ZkMetaClientFactory().getMetaClientCache(createZkMetaClientConfig(config), cacheConfig); } return null; } private ZkMetaClientConfig createZkMetaClientConfig(MetaClientConfig config) { return new ZkMetaClientConfig.ZkMetaClientConfigBuilder(). setConnectionAddress(config.getConnectionAddress()) .setMetaClientReconnectPolicy(config.getMetaClientReconnectPolicy()) .setConnectionInitTimeoutInMillis(config.getConnectionInitTimeoutInMillis()) .setSessionTimeoutInMillis(config.getSessionTimeoutInMillis()) .build(); } }
9,271
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/DataUpdater.java
package org.apache.helix.metaclient.api; /* * 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. */ /** * Updates the value of a key. This is used together with {@link MetaClientInterface.update(String key, DataUpdater<T> updater)}. * @param <T> */ public interface DataUpdater<T extends Object> { public T update(T currentData); }
9,272
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/AsyncCallback.java
package org.apache.helix.metaclient.api; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import javax.annotation.Nullable; /** * An asynchronous callback is deferred to invoke after an async CRUD operation finish and return. * The corresponding callback is registered when async CRUD API is invoked. Implementation processes * the result of each CRUD call. It should check return code and perform accordingly. */ public interface AsyncCallback { //This callback is used when stat object is returned from the operation. interface StatCallback extends AsyncCallback { /** * Process the result of asynchronous calls that returns a stat object. * @param returnCode The return code of the call. * @param key the key that passed to asynchronous calls. * @param stat the stats of the entry of the given key, returned from the async call. * Could be null if the entry did not exist. */ void processResult(int returnCode, String key, @Nullable MetaClientInterface.Stat stat); } //This callback is used when data is returned from the operation. interface DataCallback extends AsyncCallback { /** * Process the result of asynchronous calls that returns entry data. * @param returnCode The return code of the call. * @param key The key that passed to asynchronous calls. * @param data returned entry data from the call. * @param stat the stats of the entry of the given key. Could be null if the entry did not exist. */ void processResult(int returnCode, String key, byte[] data, @Nullable MetaClientInterface.Stat stat); } //This callback is used when nothing is returned from the operation. interface VoidCallback extends AsyncCallback { /** * Process the result of asynchronous calls that has no return value. * @param returnCode The return code of the call. * @param key he key that passed to asynchronous calls. */ void processResult(int returnCode, String key); } //This callback is used to process the list if OpResults from a single transactional call. interface TransactionCallback extends AsyncCallback { /** * Process the result of asynchronous transactional calls. * @param returnCode The return code of the transaction call. * @param keys List of keys passed to the async transactional call. * @param opResults The list of transactional results. */ void processResult(int returnCode, List<String> keys, List<OpResult> opResults); } }
9,273
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/DataChangeListener.java
package org.apache.helix.metaclient.api; /* * 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. */ /** * Listener interface for events on a particular key, including entry creating, deleting and value change. */ public interface DataChangeListener { enum ChangeType { ENTRY_CREATED, // Entry created of the specific path that the listener register to ENTRY_DELETED, // Entry deleted of the specific path that the listener register to ENTRY_UPDATE // Entry value updated } void handleDataChange(String key, Object data, ChangeType changeType) throws Exception; }
9,274
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/Op.java
package org.apache.helix.metaclient.api; /* * 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. */ /** * Represents a single operation in a multi-operation transaction. Each operation can be a create, set, * version check or delete operation. */ public abstract class Op { public enum Type { CREATE, DELETE, SET, CHECK } private String _path; private Type _type; private Op(Type type, String path) { this._type = type; this._path = path; } public static Op create(String path, byte[] data) { return new Create(path, data); } public static Op create(String path, byte[] data, MetaClientInterface.EntryMode createMode) { return new Create(path, data, createMode); } public static Op delete(String path, int version) { return new Op.Delete(path, version); } public static Op set(String path, byte[] data, int version) { return new Set(path, data, version); } public static Op check(String path, int version) { return new Check(path, version); } public Type getType() { return this._type; } public String getPath() { return this._path; } /** * Check the version of an entry. True only when the version is the same as expected. */ public static class Check extends Op { private final int version; public int getVersion() { return version;} private Check(String path, int version) { super(Type.CHECK, path); this.version = version; } } /** * Represents a Create operation. Creates a new node. */ public static class Create extends Op { protected final byte[] data; private MetaClientInterface.EntryMode mode; public byte[] getData() { return data; } public MetaClientInterface.EntryMode getEntryMode() {return mode;} private Create(String path, byte[] data) { super(Type.CREATE, path); this.data = data; } private Create(String path, byte[] data, MetaClientInterface.EntryMode mode) { super(Type.CREATE, path); this.data = data; this.mode = mode; } } /** * Represents a Delete operations. Deletes an existing node. */ public static class Delete extends Op{ private final int version; public int getVersion() { return version;} private Delete(String path, int version) { super(Type.DELETE, path); this.version = version; } } /** * Represents a Set operation. Sets or updates the data of a node. */ public static class Set extends Op { private final byte[] data; private final int version; public byte[] getData() { return data; } public int getVersion() { return version;} private Set(String path, byte[] data, int version) { super(Type.SET, path); this.data = data; this.version = version; } } }
9,275
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientCacheInterface.java
package org.apache.helix.metaclient.api; /* * 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 interface MetaClientCacheInterface<T> extends MetaClientInterface<T> { /** * TrieNode class to store the children of the entries to be cached. */ class TrieNode { // A mapping between trie key and children nodes. private Map<String, TrieNode> _children; // the complete path/prefix leading to the current node. private final String _path; private final String _nodeKey; public TrieNode(String path, String nodeKey) { _path = path; _nodeKey = nodeKey; _children = new HashMap<>(); } public Map<String, TrieNode> getChildren() { return _children; } public String getPath() { return _path; } public String getNodeKey() { return _nodeKey; } public void addChild(String key, TrieNode node) { _children.put(key, node); } public TrieNode processPath(String path, boolean isCreate) { String[] pathComponents = path.split("/"); TrieNode currentNode = this; TrieNode previousNode = null; for (int i = 1; i < pathComponents.length; i++) { String component = pathComponents[i]; if (component.equals(_nodeKey)) { // Skip the root node } else if (!currentNode.getChildren().containsKey(component)) { if (isCreate) { TrieNode newNode = new TrieNode(currentNode.getPath() + "/" + component, component); currentNode.addChild(component, newNode); previousNode = currentNode; currentNode = newNode; } else { return currentNode; } } else { previousNode = currentNode; currentNode = currentNode.getChildren().get(component); } } if (!isCreate && previousNode != null) { previousNode.getChildren().remove(currentNode.getNodeKey()); } return currentNode; } } }
9,276
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/OpResult.java
package org.apache.helix.metaclient.api; /* * 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; /** * Represent the result of a single operation of a multi operation transaction. */ public class OpResult { public enum Type { ERRORRESULT, GETDATARESULT, GETCHILDRENRESULT, CHECKRESULT, SETDATARESULT, DELETERESULT, CREATERESULT, CREATERESULT_WITH_STAT } private Type type; private OpResult(Type type) { this.type = type; } public Type getType() { return this.type; } /** * Represents the result of an operation that was attempted to execute but failed. */ public static class ErrorResult extends OpResult { private int err; public ErrorResult(int err) { super(Type.ERRORRESULT); this.err = err; } public int getErr() { return this.err; } } /** * Represents the result of a getData() operation. */ public static class GetDataResult extends OpResult { private byte[] data; private MetaClientInterface.Stat stat; public GetDataResult(byte[] data, MetaClientInterface.Stat stat) { super(Type.GETDATARESULT); this.data = data == null ? null : Arrays.copyOf(data, data.length); this.stat = stat; } public byte[] getData() { return this.data == null ? null : Arrays.copyOf(this.data, this.data.length); } public MetaClientInterface.Stat getStat() { return this.stat; } } /** * Represents the result of a getChildren() operation. */ public static class GetChildrenResult extends OpResult { private List<String> children; public GetChildrenResult(List<String> children) { super(Type.GETCHILDRENRESULT); this.children = children; } public List<String> getChildren() { return this.children; } } /** * Represents the result of a check() operation. */ public static class CheckResult extends OpResult { public CheckResult() { super(Type.CHECKRESULT); } } /** * Represents the result of a set() operation. */ public static class SetDataResult extends OpResult { private MetaClientInterface.Stat stat; public SetDataResult(MetaClientInterface.Stat stat) { super(Type.SETDATARESULT); this.stat = stat; } public MetaClientInterface.Stat getStat() { return this.stat; } } /** * Represents the result of a delete() operation. */ public static class DeleteResult extends OpResult { public DeleteResult() { super(Type.DELETERESULT); } } /** * Represents the result of a create() operation. */ public static class CreateResult extends OpResult { private String path; private MetaClientInterface.Stat stat; public CreateResult(String path) { this(Type.CREATERESULT, path, null); } public CreateResult(String path, MetaClientInterface.Stat stat) { this(Type.CREATERESULT_WITH_STAT, path, stat); } private CreateResult(Type type, String path, MetaClientInterface.Stat stat) { super(type); this.path = path; this.stat = stat; } public String getPath() { return this.path; } public MetaClientInterface.Stat getStat() { return this.stat; } } }
9,277
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/ChildChangeListener.java
package org.apache.helix.metaclient.api; /* * 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. */ /** * Listener interface for children change events on a particular key. It includes new child * creation, child deletion, child data change. * TODO: add type for persist listener is removed * For hierarchy key spaces like zookeeper, it refers to an entry's entire subtree. * For flat key spaces, it refers to keys that matches `prefix*`. */ public interface ChildChangeListener { enum ChangeType { ENTRY_CREATED, // Any child entry created ENTRY_DELETED, // Any child entry deleted ENTRY_DATA_CHANGE // Any child entry has value change } /** * Called when any child of the current key has changed. */ void handleChildChange(String changedPath, ChangeType changeType) throws Exception; }
9,278
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/DirectChildChangeListener.java
package org.apache.helix.metaclient.api; /* * 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. */ /** * Listener interface for direct child change event on a particular key. It includes new * child creation or child deletion. The callback won't differentiate these types. * For hierarchy key spaces like zookeeper, it refers to an entry's direct child nodes. * For flat key spaces, it refers to keys that matches `prefix*separator`. */ public interface DirectChildChangeListener { /** * Called when there is a direct child entry creation or deleted. * @param key The parent key where child change listener is subscribed. It would be the key * passed to subscribeDirectChildChange. * @throws Exception */ void handleDirectChildChange(String key) throws Exception; }
9,279
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/DirectChildSubscribeResult.java
package org.apache.helix.metaclient.api; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; public class DirectChildSubscribeResult { // A list of direct children names at the time when change is subscribed. // It includes only one level child name, does not include further sub children names. private final List<String> _children; // true means the listener is registered successfully. private final boolean _isRegistered; public DirectChildSubscribeResult(List<String> children, boolean isRegistered) { _children = children; _isRegistered = isRegistered; } public List<String> getDirectChildren() { return _children; } public boolean isRegistered() { return _isRegistered; } }
9,280
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/ConnectStateChangeListener.java
package org.apache.helix.metaclient.api; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public interface ConnectStateChangeListener { /** * Called when the connection state has changed. I * @param prevState previous state before state change event. * @param currentState client state after state change event. If it is a one time listsner, it is * possible that the metaclient state changes again */ void handleConnectStateChanged(MetaClientInterface.ConnectState prevState, MetaClientInterface.ConnectState currentState) throws Exception; /** * Called when new connection failed to established. * @param error error returned from metaclient or metadata service. */ void handleConnectionEstablishmentError(final Throwable error) throws Exception; // TODO: Consider add a callback for new connection when we add support for session ID. }
9,281
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java
package org.apache.helix.metaclient.api; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.helix.metaclient.exception.MetaClientInterruptException; import org.apache.helix.metaclient.exception.MetaClientNoNodeException; import org.apache.helix.metaclient.exception.MetaClientTimeoutException; public interface MetaClientInterface<T> { enum EntryMode { // The node will be removed automatically when the session associated with the creation // of the node expires. EPHEMERAL, // The node will not be automatically deleted upon client's disconnect. // An ephemeral node cannot have sub entry. PERSISTENT, // For metadata storage that has hierarchical key space (e.g. ZK), the node will be // automatically deleted at some point in the future if the last child of the node is deleted. // For metadata storage that has non-hierarchical key space (e.g. etcd), the node will be // automatically deleted at some point in the future if the last entry that has the prefix // is deleted. // The node is an ephemeral node. CONTAINER, // For metadata storage that has hierarchical key space (e.g. ZK) If the entry is not modified // within the TTL and has no children it will become a candidate to be deleted by the server // at some point in the future. // For metadata storage that has non-hierarchical key space (e.g. etcd) If the entry is not modified // within the TTL, it will become a candidate to be deleted by the server at some point in the // future. TTL } enum ConnectState { // Client is not connected to server. Before initiating connection or after close. NOT_CONNECTED, // Client is connected to server CONNECTED, // Authentication failed. AUTH_FAILED, // Server has expired this connection. EXPIRED, // When client explicitly call disconnect. CLOSED_BY_CLIENT, // Connection between client and server is lost. DISCONNECTED, // Client is authenticated. They can perform operation with authorized permissions. // This state is not in use as of now. AUTHENTICATED } /** * Interface representing the metadata of an entry. It contains entry type and version number. * TODO: we will add session ID to entry stats in the future * TODO: Add support for expiry time */ class Stat { private final int _version; private final EntryMode _entryMode; // The expiry time of a TTL node in milliseconds. The default is -1 for nodes without expiry time. private long _expiryTime; // The time when the node is created. Measured in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). private long _creationTime; // The time when the node was las modified. Measured in milliseconds since the Unix epoch when the node was last modified. private long _modifiedTime; public EntryMode getEntryType() { return _entryMode; } public int getVersion() { return _version; } public long getExpiryTime() { return _expiryTime; } public long getCreationTime() { return _creationTime; } public long getModifiedTime() { return _modifiedTime; } public Stat (EntryMode mode, int version) { _version = version; _entryMode = mode; _expiryTime = -1; } public Stat (EntryMode mode, int version, long ctime, long mtime, long etime) { _version = version; _entryMode = mode; _creationTime = ctime; _modifiedTime = mtime; _expiryTime = etime; } } //synced CRUD API /** * Create a persistent entry with given key and data. The entry will not be created if there is * an existing entry with the same key. * @param key key to identify the entry * @param data value of the entry */ void create(final String key, T data); /** * Create an entry of given EntryMode with given key and data. The entry will not be created if * there is an existing entry with ethe same key. * @param key key to identify the entry * @param data value of the entry * @param mode EntryMode identifying if the entry will be deleted upon client disconnect */ void create(final String key, final T data, final EntryMode mode); /** * Create an entry of given EntryMode with given key and data. If any parent node in the node * hierarchy does not exist, then the parent node will attempt to be created. The entry will not * be created if there is an existing entry with the same full key. Ephemeral nodes cannot have * children, so only the final child in the created path will be ephemeral. */ void recursiveCreate(final String key, final T Data, final EntryMode mode); /** * Create a TTL entry with given key, data, and expiry time (ttl). If any parent node in the node * hierarchy does not exist, then the parent node will attempt to be created. The entry will not be created if * there is an existing entry with the same full key. */ void recursiveCreateWithTTL(String key, T data, long ttl); /** * Create an entry of given EntryMode with given key, data, and expiry time (ttl). * The entry will automatically purge when reached expiry time and has no children. * The entry will not be created if there is an existing entry with the same key. * @param key key to identify the entry * @param data value of the entry * @param ttl Time-to-live value of the node in milliseconds. */ void createWithTTL(final String key, final T data, final long ttl); /** * Renews the specified TTL node adding its original expiry time * to the current time. Throws an exception if the key is not a valid path * or isn't of type TTL. * @param key key to identify the entry */ void renewTTLNode(final String key); /** * Set the data for the entry of the given key if it exists and the given version matches the * version of the node (if the given version is -1, it matches any node's versions). * @param key key to identify the entry * @param data new data of the entry * @param version expected version of the entry. -1 matched any version. */ void set(final String key, final T data, int version); /** * Update existing data of a given key using an updater. This method will issue a read to get * current data and apply updater upon the current data. * @param key key to identify the entry * @param updater An updater that modifies the entry value. * @return the updated value. */ T update(final String key, DataUpdater<T> updater); /** * Check if there is an entry for the given key. * @param key key to identify the entry * @return return a Stat object if the entry exists. Return null otherwise. */ Stat exists(final String key); /** * Fetch the data for a given key. * @param key key to identify the entry * @return Return data of the entry. Return null if data does not exists. */ T get(final String key); /** * Fetch the data and stat for a given key. * @param key key to identify the entry * @return Return an ImmutablePair of data and stat for the entry. * @throws MetaClientNoNodeException if no such entry */ ImmutablePair<T, Stat> getDataAndStat(final String key); /** * API for transaction. The list of operation will be executed as an atomic operation. * @param ops a list of operations. These operations will all be executed or none of them. * @return Return a list of OpResult. */ List<OpResult> transactionOP(final Iterable<Op> ops); /** * Return a list of children for the given keys. * @param key For metadata storage that has hierarchical key space (e.g. ZK), the key would be * a parent key, * For metadata storage that has non-hierarchical key space (e.g. etcd), the key would * be a prefix key. * @return Return a list of children keys. Return direct child name only for hierarchical key * space, return the whole sub key for non-hierarchical key space. */ List<String> getDirectChildrenKeys(final String key); /** * Return the number of children for the given keys. * @param key For metadata storage that has hierarchical key space (e.g. ZK), the key would be * a parent key, * For metadata storage that has non-hierarchical key space (e.g. etcd), the key would * be a prefix key. */ int countDirectChildren(final String key); /** * Remove the entry associated with the given key. * For metadata storage that has hierarchical key space, the entry can only be deleted if the key * has no child entry. * TODO: define exception to throw * @param key key to identify the entry to delete * @return Return true if the deletion is completed */ boolean delete(final String key); /** * Remove the entry associated with the given key. * For metadata storage that has hierarchical key space, remove all its child entries as well * For metadata storage that has non-hierarchical key space, this API is the same as delete() * @param key key to identify the entry to delete * @return Return true if the deletion is completed */ boolean recursiveDelete(final String key); /* Asynchronous methods return immediately. * They take a callback object that will be executed either on successful execution of the request * or on error with an appropriate return code indicating the error. */ /** * User may register callbacks for async CRUD calls. These callbacks will be executed in a async * thread pool. User could define the thread pool size. Default value is 10. * TODO: add const default value in a separate file * @param poolSize pool size for executing user resisted async callbacks */ void setAsyncExecPoolSize(int poolSize); /** * The asynchronous version of create. * @param key key to identify the entry * @param data value of the entry * @param mode EntryMode identifying if the entry will be deleted upon client disconnect * @param cb A user defined VoidCallback implementation that will be invoked when async create return. * @see org.apache.helix.metaclient.api.AsyncCallback.VoidCallback */ void asyncCreate(final String key, final T data, final EntryMode mode, AsyncCallback.VoidCallback cb); /** * The asynchronous version of set. * @param key key to identify the entry * @param data new data of the entry * @param version expected version if the entry. -1 matched any version * @param cb A user defined VoidCallback implementation that will be invoked when async create return. * @see org.apache.helix.metaclient.api.AsyncCallback.StatCallback */ void asyncSet(final String key, final T data, final int version, AsyncCallback.StatCallback cb); /** * The asynchronous version of update. * @param key key to identify the entry * @param updater An updater that modifies the entry value. * @param cb A user defined VoidCallback implementation that will be invoked when async create return. * It will contain the newly updated data if update succeeded. * @see org.apache.helix.metaclient.api.AsyncCallback.DataCallback */ void asyncUpdate(final String key, DataUpdater<T> updater, AsyncCallback.DataCallback cb); /** * The asynchronous version of get. * @param key key to identify the entry * @param cb A user defined VoidCallback implementation that will be invoked when async get return. * It will contain the entry data if get succeeded. * @see org.apache.helix.metaclient.api.AsyncCallback.DataCallback */ void asyncGet(final String key, AsyncCallback.DataCallback cb); /** * The asynchronous version of get sub entries. * @param key key to identify the entry * @param cb A user defined VoidCallback implementation that will be invoked when async count child return. * It will contain the list of child keys if succeeded. * @see org.apache.helix.metaclient.api.AsyncCallback.DataCallback */ void asyncCountChildren(final String key, AsyncCallback.DataCallback cb); /** * The asynchronous version of get sub entries. * @param key key to identify the entry * @param cb A user defined VoidCallback implementation that will be invoked when async exist return. * It will contain the stats of the entry if succeeded. * @see org.apache.helix.metaclient.api.AsyncCallback.StatCallback */ void asyncExist(final String key, AsyncCallback.StatCallback cb); /** * The asynchronous version of delete. * @param key key to identify the entry * @param cb A user defined VoidCallback implementation that will be invoked when async delete * finish and return. @see org.apache.helix.metaclient.api.AsyncCallback.DataCallback */ void asyncDelete(final String key, AsyncCallback.VoidCallback cb); /** * The asynchronous version of transaction operations. * @param ops A list of operations * @param cb A user defined TransactionCallback implementation that will be invoked when * transaction operations finish and return. The TransactionCallback will contain * either a list of OpResult if transaction finish successfully, or a return code * indicating failure reason. @see org.apache.helix.metaclient.api.AsyncCallback.TransactionCallback */ void asyncTransaction(final Iterable<Op> ops, AsyncCallback.TransactionCallback cb); /* Batched APIs return result to user when all request finishes. * These calls are not executed as a transaction. */ /** * Batch version of create. All entries will be created in persist mode. Returns when all request * finishes. These calls are not executed as a transaction. * @param key A list of key for create operations. * @param data A list of data. Need to be in the same length of list of key. * @return A list of boolean indicating create result of each operation. */ boolean[] create(List<String> key, List<T> data); /** * Batch version of create. Returns when all request finishes. These calls are not executed as a * transaction. * @param key A list of key for create operations. * @param data A list of data. Need to be in the same length of list of key. * @param mode A list of EntryMode. Need to be in the same length of list of key. * @return A list of boolean indicating create result of each operation. */ boolean[] create(List<String> key, List<T> data, List<EntryMode> mode); /** * Batch version of set. Returns when all request finishes. These calls are not executed as a * transaction. * @param keys A list of key for set operations. * @param datas A list of data. Need to be in the same length of list of key. * @param version A list of expected version of the entry. -1 matched any version. * Need to be in the same length of list of key. * @return A list of boolean indicating set result of each operation. */ boolean[] set(List<String> keys, List<T> datas, List<Integer> version); /** * Batch version of update. Returns when all request finishes. These calls are not executed as a * transaction. * @param keys A list of key for update operations. * @param updater A list of updater. Need to be in the same length of list of key. * @return A list of updated entry values. */ List<T> update(List<String> keys, List<DataUpdater<T>> updater); /** * Batch version of get. Returns when all request finishes. These calls are not executed as a * transaction. * @param keys A list of key for get operations. * @return A list of entry values. */ List<T> get(List<String> keys); /** * Batch version of exists. Returns when all request finishes. These calls are not executed as a * transaction. * @param keys A list of key for exists operations. * @return A list of stats for the given entries. */ List<Stat> exists(List<String> keys); /** * Batch version of delete. Returns when all request finishes. These calls are not executed as a * transaction. * @param keys A list of key for delete operations. * @return A list of boolean indicating delete result of each operation. */ boolean[] delete(List<String> keys); /** * Maintains a connection with underlying metadata service based on config params. Connection * created by this method will be used to perform CRUD operations on metadata service. * @throws MetaClientInterruptException * if the connection timed out due to thread interruption * @throws MetaClientTimeoutException * if the connection timed out * @throws IllegalStateException * if already connected or the connection is already closed explicitly */ void connect(); /** * Disconnect from server explicitly. */ void disconnect(); /** * Check whether client is closed * @return true if client is closed, false otherwise */ boolean isClosed(); /** * @return client current connection state with metadata service. */ ConnectState getClientConnectionState(); // Event notification APIs, user can register multiple listeners on the same key/connection state. // All listeners will be automatically removed when client is disconnected. // TODO: add auto re-register listener option /** * Subscribe change of a particular entry. Including entry data change, entry deletion and creation * of the given key. * The listener should be permanent until it's unsubscribed. * @param key Key to identify the entry * @param listener An implementation of {@link org.apache.helix.metaclient.api.DataChangeListener} to register * @param skipWatchingNonExistNode Will not register lister to a non-exist key if set to true. * Please set to false if you are expecting ENTRY_CREATED type. * @return Return a boolean indication if subscribe succeeded. */ boolean subscribeDataChange(String key, DataChangeListener listener, boolean skipWatchingNonExistNode); /** * Subscribe a one-time change of a particular entry. Including entry data change, entry deletion and creation * of the given key. * The implementation should use at-most-once delivery semantic. * @param key Key to identify the entry * @param listener An implementation of {@link org.apache.helix.metaclient.api.DataChangeListener} to register * @param skipWatchingNonExistNode Will not register lister to a non-exist key if set to true. * Please set to false if you are expecting ENTRY_CREATED type. * @return Return a boolean indication if subscribe succeeded. */ default boolean subscribeOneTimeDataChange(String key, DataChangeListener listener, boolean skipWatchingNonExistNode) { throw new NotImplementedException("subscribeOneTimeDataChange is not implemented"); } /** * Subscribe for direct child change event on a particular key. It includes new child * creation or deletion. It does not include existing child data change. * The listener should be permanent until it's unsubscribed. * For hierarchy key spaces like zookeeper, it refers to an entry's direct children nodes. * For flat key spaces, it refers to keys that matches `prefix*separator`. * @param key key to identify the entry. * @param listener An implementation of {@link org.apache.helix.metaclient.api.DirectChildChangeListener} to register * @param skipWatchingNonExistNode If the passed in key does not exist, no listener wil be registered. * * @return Return a DirectChildSubscribeResult. It will contain a list of direct sub children if * subscribe succeeded. */ DirectChildSubscribeResult subscribeDirectChildChange(String key, DirectChildChangeListener listener, boolean skipWatchingNonExistNode); /** * Subscribe for a one-time direct child change event on a particular key. It includes new child * creation or deletion. It does not include existing child data change. * The implementation should use at-most-once delivery semantic. * For hierarchy key spaces like zookeeper, it refers to an entry's direct children nodes. * For flat key spaces, it refers to keys that matches `prefix*separator`. * * @param key key to identify the entry. * @param listener An implementation of {@link org.apache.helix.metaclient.api.DirectChildChangeListener} to register * @param skipWatchingNonExistNode If the passed in key does not exist, no listener wil be registered. * * @return Return a DirectChildSubscribeResult. It will contain a list of direct sub children if * subscribe succeeded. */ default DirectChildSubscribeResult subscribeOneTimeDirectChildChange(String key, DirectChildChangeListener listener, boolean skipWatchingNonExistNode) { throw new NotImplementedException("subscribeOneTimeDirectChildChange is not implemented"); } /** * Subscribe for connection state change. * The listener should be permanent until it's unsubscribed. * @param listener An implementation of {@link org.apache.helix.metaclient.api.ConnectStateChangeListener} to register * * @return Return a boolean indication if subscribe succeeded. */ boolean subscribeStateChanges(ConnectStateChangeListener listener); /** * Subscribe change for all children including entry change and data change. * The listener should be permanent until it's unsubscribed. * For hierarchy key spaces like zookeeper, it would watch the whole tree structure. * For flat key spaces, it would watch for keys with certain prefix. * @param key key to identify the entry. * @param listener An implementation of {@link org.apache.helix.metaclient.api.ChildChangeListener} to register * @param skipWatchingNonExistNode If the passed in key does not exist, no listener wil be registered. */ boolean subscribeChildChanges(String key, ChildChangeListener listener, boolean skipWatchingNonExistNode); /** * Subscribe a one-time change for all children including entry change and data change. * The implementation should use at-most-once delivery semantic. * For hierarchy key spaces like zookeeper, it would watch the whole tree structure. * For flat key spaces, it would watch for keys with certain prefix. * @param key key to identify the entry. * @param listener An implementation of {@link org.apache.helix.metaclient.api.ChildChangeListener} to register * @param skipWatchingNonExistNode If the passed in key does not exist, no listener wil be registered. */ default boolean subscribeOneTimeChildChanges(String key, ChildChangeListener listener, boolean skipWatchingNonExistNode) { throw new NotImplementedException("subscribeOneTimeChildChanges is not implemented"); } /** * Unsubscribe the listener to further changes. No-op if the listener is not subscribed to the key. * @param key Key to identify the entry. * @param listener The listener to unsubscribe. */ void unsubscribeDataChange(String key, DataChangeListener listener); /** * Unsubscribe the listener to further changes. No-op if the listener is not subscribed to the key. * @param key Key to identify the entry. * @param listener The listener to unsubscribe. */ void unsubscribeDirectChildChange(String key, DirectChildChangeListener listener); /** * Unsubscribe the listener to further changes. No-op if the listener is not subscribed to the key. * @param key Key to identify the entry. * @param listener The listener to unsubscribe. */ void unsubscribeChildChanges(String key, ChildChangeListener listener); /** * Unsubscribe the listener to further changes. No-op if the listener is not subscribed to the key. * @param listener The listener to unsubscribe. */ void unsubscribeConnectStateChanges(ConnectStateChangeListener listener); /** * Block the call until the given key exists or timeout. * @param key Key to monitor. * @param timeUnit timeout unit * @param timeOut timeout value * @return */ boolean waitUntilExists(String key, TimeUnit timeUnit, long timeOut); /** * Serialize the data in type T to a byte array. This function can be used in API that returns or * has input value in byte array format. * @param data to be serialized. * @param path timeout unit * @return */ byte[] serialize(T data, String path); /** * Serialize a byte array to data in type T. This function can be used in API that returns or * has input value in byte array format. * @param bytes to be deserialized. * @param path timeout unit * @return */ T deserialize(byte[] bytes, String path); // TODO: Secure CRUD APIs }
9,282
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/datamodel/DataRecord.java
package org.apache.helix.metaclient.datamodel; /* * 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.fasterxml.jackson.databind.annotation.JsonSerialize; import org.apache.helix.metaclient.recipes.leaderelection.LeaderInfo; import org.apache.helix.zookeeper.datamodel.ZNRecord; /** * The DataRecord object is a wrapper around ZNRecord. * TODO: Create an interface to decouple DataRecord and have a pluggable record store. */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class DataRecord extends ZNRecord { public DataRecord(String znodeId) { super(znodeId); } public DataRecord(ZNRecord record) { super(record); } public DataRecord(DataRecord record, String id) { super(record, id); } }
9,283
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientBadVersionException.java
package org.apache.helix.metaclient.exception; public final class MetaClientBadVersionException extends MetaClientException { public MetaClientBadVersionException() { super(); } public MetaClientBadVersionException(String message, Throwable cause) { super(message, cause); } public MetaClientBadVersionException(String message) { super(message); } public MetaClientBadVersionException(Throwable cause) { super(cause); } }
9,284
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientNoNodeException.java
package org.apache.helix.metaclient.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public final class MetaClientNoNodeException extends MetaClientException { public MetaClientNoNodeException() { super(); } public MetaClientNoNodeException(String message, Throwable cause) { super(message, cause); } public MetaClientNoNodeException(String message) { super(message); } public MetaClientNoNodeException(Throwable cause) { super(cause); } }
9,285
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientTimeoutException.java
package org.apache.helix.metaclient.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public final class MetaClientTimeoutException extends MetaClientException { public MetaClientTimeoutException() { super(); } public MetaClientTimeoutException(String message, Throwable cause) { super(message, cause); } public MetaClientTimeoutException(String message) { super(message); } public MetaClientTimeoutException(Throwable cause) { super(cause); } }
9,286
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientNodeExistsException.java
package org.apache.helix.metaclient.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public final class MetaClientNodeExistsException extends MetaClientException { public MetaClientNodeExistsException() { super(); } public MetaClientNodeExistsException(String message, Throwable cause) { super(message, cause); } public MetaClientNodeExistsException(String message) { super(message); } public MetaClientNodeExistsException(Throwable cause) { super(cause); } }
9,287
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientInterruptException.java
package org.apache.helix.metaclient.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public final class MetaClientInterruptException extends MetaClientException { public MetaClientInterruptException() { super(); } public MetaClientInterruptException(String message, Throwable cause) { super(message, cause); } public MetaClientInterruptException(String message) { super(message); } public MetaClientInterruptException(Throwable cause) { super(cause); } }
9,288
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientException.java
package org.apache.helix.metaclient.exception; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public class MetaClientException extends RuntimeException { public MetaClientException() { super(); } public MetaClientException(String message, Throwable cause) { super(message, cause); } public MetaClientException(String message) { super(message); } public MetaClientException(Throwable cause) { super(cause); } public enum ReturnCode { /** Connection to the server has been lost. */ CONNECTION_LOSS(-105, "Connection to the server has been lost.") , /** Operation is unimplemented. */ UNIMPLEMENTED(-104, "Operation is unimplemented."), /** Operation timeout. */ OPERATION_TIMEOUT(-103, "Operation timeout.") { @Override public MetaClientException createMetaClientException() { return new MetaClientTimeoutException(); } }, /** Either a runtime or data inconsistency was found. */ CONSISTENCY_ERROR(-102, "Inconsistency was found."), /** Session is moved or expired or non-exist. */ SESSION_ERROR(-101, "Session is moved or expired or non-exist."), /** Indicates a system and server-side errors not defined by following codes. * It also indicate a range. Any value smaller or equal than this indicating error from * server side. */ DB_SYSTEM_ERROR(-100, "System and server-side errors."), /** The listener does not exists. */ INVALID_LISTENER(-9, "Listener does not exists."), /** Authentication failed. */ AUTH_FAILED(-8, "authentication failed"), /** Invalid arguments. */ INVALID_ARGUMENTS(-7, "Invalid arguments"), /** Version conflict. Return when caller tries to edit an entry with a specific version but * the actual version of the entry on server is different. */ BAD_VERSION(-6, "Version conflict.") { @Override public MetaClientException createMetaClientException() { return new MetaClientBadVersionException(); } }, /** Entry already exists. Return when try to create a duplicated entry. */ ENTRY_EXISTS(-5, "Entry already exists."), /** The client is not Authenticated. */ NO_AUTH(-4, "Not Authenticated.") , /** Entry does not exist. */ NO_SUCH_ENTRY(-3, "Entry does not exist.") { @Override public MetaClientException createMetaClientException() { return new MetaClientNoNodeException(); } }, /**The entry has sub entries. Return when operation can only be down at entry with no * sub entries. (i.e. unrecursively delete an entry . )*/ NOT_LEAF_ENTRY(-2, "The entry has sub entries."), /** Indicates a system and DB client or a usage errors not defined by following codes. * It also indicate a range. Any value smaller or equal than this and larger than * DB_SYSTEM_ERROR indicating error from client or caused by wrong usage. */ DB_USER_ERROR(-1, "Client or usage error."), /** Everything is OK. */ OK(0, "OK") { @Override public MetaClientException createMetaClientException() { return null; } }; private final int _intValue; private final String _message; ReturnCode(int codeIntValue, String message) { _intValue = codeIntValue; _message = message; } public String getMessage() { return _message; } public int getIntValue() { return _intValue; } public MetaClientException createMetaClientException() { // TODO: add more code translation when new exception class is created. return new MetaClientException(); } } }
9,289
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/policy/ExponentialBackoffReconnectPolicy.java
package org.apache.helix.metaclient.policy; /* * 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.metaclient.policy.MetaClientReconnectPolicy; import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_AUTO_RECONNECT_TIMEOUT_MS; import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_INIT_EXP_BACKOFF_RETRY_INTERVAL_MS; import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_MAX_EXP_BACKOFF_RETRY_INTERVAL_MS; /** * Policy to define client re-establish connection behavior when connection to underlying metadata * store is expired. * Wait time before each backoff period will increase exponentially until a user defined max * backoff interval. */ public class ExponentialBackoffReconnectPolicy implements MetaClientReconnectPolicy { private final long _autoReconnectTimeout; @Override public RetryPolicyName getPolicyName() { return RetryPolicyName.EXP_BACKOFF; } @Override public long getAutoReconnectTimeout() { return _autoReconnectTimeout; } public ExponentialBackoffReconnectPolicy() { _autoReconnectTimeout = DEFAULT_AUTO_RECONNECT_TIMEOUT_MS; } public ExponentialBackoffReconnectPolicy(long autoReconnectTimeout) { _autoReconnectTimeout = autoReconnectTimeout; } // TODO: Allow user to pass maxBackOffInterval and initBackoffInterval. }
9,290
0
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient
Create_ds/helix/meta-client/src/main/java/org/apache/helix/metaclient/policy/MetaClientReconnectPolicy.java
package org.apache.helix.metaclient.policy; /* * 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 static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_AUTO_RECONNECT_TIMEOUT_MS; /** * Policy to define client re-establish connection behavior when connection to underlying metadata * store is expired. */ public interface MetaClientReconnectPolicy { enum RetryPolicyName { EXP_BACKOFF, LINEAR_BACKOFF } RetryPolicyName getPolicyName(); default long getAutoReconnectTimeout() { return DEFAULT_AUTO_RECONNECT_TIMEOUT_MS; } }
9,291
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/clusterMaintenanceService/TestMaintenanceManagementService.java
package org.apache.helix.rest.clusterMaintenanceService; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.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 com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.apache.helix.AccessOption; import org.apache.helix.BaseDataAccessor; import org.apache.helix.ConfigAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.LeaderStandbySMD; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.model.RESTConfig; import org.apache.helix.rest.client.CustomRestClient; import org.apache.helix.rest.common.HelixDataAccessorWrapper; import org.apache.helix.rest.common.HelixRestNamespace; import org.apache.helix.rest.server.json.instance.StoppableCheck; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.zookeeper.data.Stat; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class TestMaintenanceManagementService { private static final String TEST_CLUSTER = "TestCluster"; private static final String TEST_INSTANCE = "instance0.linkedin.com_1235"; @Mock private HelixDataAccessorWrapper _dataAccessorWrapper; @Mock private ConfigAccessor _configAccessor; @Mock private CustomRestClient _customRestClient; @BeforeMethod public void beforeMethod() { MockitoAnnotations.initMocks(this); RESTConfig restConfig = new RESTConfig("restConfig"); restConfig.set(RESTConfig.SimpleFields.CUSTOMIZED_HEALTH_URL, "http://*:123/path"); when(_configAccessor.getRESTConfig(TEST_CLUSTER)).thenReturn(restConfig); } class MockMaintenanceManagementService extends MaintenanceManagementService { public MockMaintenanceManagementService(ZKHelixDataAccessor dataAccessor, ConfigAccessor configAccessor, CustomRestClient customRestClient, boolean skipZKRead, boolean continueOnFailure, String namespace) { super(new HelixDataAccessorWrapper(dataAccessor, customRestClient, namespace), configAccessor, customRestClient, skipZKRead, continueOnFailure ? Collections.singleton(ALL_HEALTH_CHECK_NONBLOCK) : Collections.emptySet(), null, namespace); } public MockMaintenanceManagementService(HelixDataAccessorWrapper dataAccessorWrapper, ConfigAccessor configAccessor, CustomRestClient customRestClient, boolean skipZKRead, boolean continueOnFailure, Set<StoppableCheck.Category> skipHealthCheckCategories, String namespace) { super(dataAccessorWrapper, configAccessor, customRestClient, skipZKRead, continueOnFailure ? Collections.singleton(ALL_HEALTH_CHECK_NONBLOCK) : Collections.emptySet(), skipHealthCheckCategories, namespace); } public MockMaintenanceManagementService(ZKHelixDataAccessor dataAccessor, ConfigAccessor configAccessor, CustomRestClient customRestClient, boolean skipZKRead, Set<String> nonBlockingHealthChecks, String namespace) { super(new HelixDataAccessorWrapper(dataAccessor, customRestClient, namespace), configAccessor, customRestClient, skipZKRead, nonBlockingHealthChecks, null, namespace); } @Override protected Map<String, Boolean> getInstanceHealthStatus(String clusterId, String instanceName, List<HealthCheck> healthChecks) { return Collections.emptyMap(); } } @Test public void testGetInstanceStoppableCheckWhenHelixOwnCheckFail() throws IOException { Map<String, Boolean> failedCheck = ImmutableMap.of("FailCheck", false); MockMaintenanceManagementService service = new MockMaintenanceManagementService(_dataAccessorWrapper, _configAccessor, _customRestClient, false, false, HelixRestNamespace.DEFAULT_NAMESPACE_NAME) { @Override protected Map<String, Boolean> getInstanceHealthStatus(String clusterId, String instanceName, List<HealthCheck> healthChecks) { return failedCheck; } }; String jsonContent = ""; StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, jsonContent); Assert.assertEquals(actual.getFailedChecks().size(), failedCheck.size()); Assert.assertFalse(actual.isStoppable()); verifyZeroInteractions(_customRestClient); verifyZeroInteractions(_configAccessor); } @Test public void testGetInstanceStoppableCheckWhenCustomInstanceCheckFail() throws IOException { MockMaintenanceManagementService service = new MockMaintenanceManagementService(_dataAccessorWrapper, _configAccessor, _customRestClient, false, false, HelixRestNamespace.DEFAULT_NAMESPACE_NAME) { @Override protected Map<String, Boolean> getInstanceHealthStatus(String clusterId, String instanceName, List<HealthCheck> healthChecks) { return Collections.emptyMap(); } }; Map<String, Boolean> failedCheck = ImmutableMap.of("FailCheck", false); when(_customRestClient.getInstanceStoppableCheck(anyString(), anyMap())).thenReturn( failedCheck); String jsonContent = "{\n" + " \"param1\": \"value1\",\n" + "\"param2\": \"value2\"\n" + "}"; StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, jsonContent); Assert.assertFalse(actual.isStoppable()); Assert.assertEquals(actual.getFailedChecks().size(), failedCheck.size()); verify(_customRestClient, times(1)).getInstanceStoppableCheck(any(), any()); verify(_customRestClient, times(0)).getPartitionStoppableCheck(any(), any(), any()); } @Test public void testGetInstanceStoppableCheckWhenCustomInstanceCheckAndCustomPartitionCheckDisabled() throws IOException { // Test when custom instance and partition check are both disabled. MockMaintenanceManagementService service = new MockMaintenanceManagementService(_dataAccessorWrapper, _configAccessor, _customRestClient, false, false, new HashSet<>( Arrays.asList(StoppableCheck.Category.CUSTOM_INSTANCE_CHECK, StoppableCheck.Category.CUSTOM_PARTITION_CHECK)), HelixRestNamespace.DEFAULT_NAMESPACE_NAME); StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, ""); Assert.assertTrue(actual.isStoppable()); verify(_dataAccessorWrapper, times(0)).getAllPartitionsHealthOnLiveInstance(any(), any(), anyBoolean()); verify(_customRestClient, times(0)).getInstanceStoppableCheck(any(), any()); } @Test public void testGetInstanceStoppableCheckWhenCustomPartitionCheckDisabled() throws IOException { // Test when custom only partition check is disabled and instance check fails. when(_dataAccessorWrapper.getAllPartitionsHealthOnLiveInstance(any(), anyMap(), anyBoolean())).thenReturn(Collections.emptyMap()); when(_dataAccessorWrapper.getChildValues(any(), anyBoolean())).thenReturn( Collections.emptyList()); when(_customRestClient.getInstanceStoppableCheck(anyString(), anyMap())).thenReturn( ImmutableMap.of("FailCheck", false)); MockMaintenanceManagementService service = new MockMaintenanceManagementService(_dataAccessorWrapper, _configAccessor, _customRestClient, false, false, new HashSet<>(Arrays.asList(StoppableCheck.Category.CUSTOM_PARTITION_CHECK)), HelixRestNamespace.DEFAULT_NAMESPACE_NAME); StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, ""); Assert.assertEquals(actual.getFailedChecks(), Arrays.asList(StoppableCheck.Category.CUSTOM_INSTANCE_CHECK.getPrefix() + "FailCheck")); Assert.assertFalse(actual.isStoppable()); verify(_dataAccessorWrapper, times(0)).getAllPartitionsHealthOnLiveInstance(any(), any(), anyBoolean()); verify(_customRestClient, times(1)).getInstanceStoppableCheck(any(), any()); } @Test public void testGetInstanceStoppableCheckWhenCustomInstanceCheckDisabled() throws IOException { // Test when custom only instance check is disabled and partition check fails. String testResource = "testResource"; ZNRecord externalViewZnode = new ZNRecord(testResource); externalViewZnode.setSimpleField( ExternalView.ExternalViewProperty.STATE_MODEL_DEF_REF.toString(), LeaderStandbySMD.name); ExternalView externalView = new ExternalView(externalViewZnode); externalView.setStateMap("testPartition", ImmutableMap.of(TEST_INSTANCE, "LEADER", "sibling_instance", "OFFLINE")); when(_dataAccessorWrapper.getAllPartitionsHealthOnLiveInstance(any(), anyMap(), anyBoolean())).thenReturn(Collections.emptyMap()); when(_dataAccessorWrapper.getProperty((PropertyKey) any())).thenReturn(new LeaderStandbySMD()); when(_dataAccessorWrapper.keyBuilder()).thenReturn(new PropertyKey.Builder(TEST_CLUSTER)); when(_dataAccessorWrapper.getChildValues(any(), anyBoolean())).thenReturn( Arrays.asList(externalView)); MockMaintenanceManagementService service = new MockMaintenanceManagementService(_dataAccessorWrapper, _configAccessor, _customRestClient, false, false, new HashSet<>(Arrays.asList(StoppableCheck.Category.CUSTOM_INSTANCE_CHECK)), HelixRestNamespace.DEFAULT_NAMESPACE_NAME); StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, ""); List<String> expectedFailedChecks = Arrays.asList( StoppableCheck.Category.CUSTOM_PARTITION_CHECK.getPrefix() + "PARTITION_INITIAL_STATE_FAIL:testPartition"); Assert.assertEquals(actual.getFailedChecks(), expectedFailedChecks); Assert.assertFalse(actual.isStoppable()); verify(_dataAccessorWrapper, times(1)).getAllPartitionsHealthOnLiveInstance(any(), any(), anyBoolean()); verify(_customRestClient, times(0)).getInstanceStoppableCheck(any(), any()); } @Test public void testGetInstanceStoppableCheckConnectionRefused() throws IOException { MockMaintenanceManagementService service = new MockMaintenanceManagementService(_dataAccessorWrapper, _configAccessor, _customRestClient, false, false, HelixRestNamespace.DEFAULT_NAMESPACE_NAME) { @Override protected Map<String, Boolean> getInstanceHealthStatus(String clusterId, String instanceName, List<HealthCheck> healthChecks) { return Collections.emptyMap(); } }; when(_customRestClient.getInstanceStoppableCheck(anyString(), anyMap())) .thenThrow(IOException.class); Map<String, String> dataMap = ImmutableMap.of("instance", TEST_INSTANCE, "selection_base", "zone_based"); String jsonContent = new ObjectMapper().writeValueAsString(dataMap); StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, jsonContent); int expectedFailedChecksSize = 1; String expectedFailedCheck = StoppableCheck.Category.CUSTOM_INSTANCE_CHECK.getPrefix() + TEST_INSTANCE; Assert.assertNotNull(actual); Assert.assertFalse(actual.isStoppable()); Assert.assertEquals(actual.getFailedChecks().size(), expectedFailedChecksSize); Assert.assertEquals(actual.getFailedChecks().get(0), expectedFailedCheck); } @Test public void testCustomPartitionCheckWithSkipZKRead() throws IOException { // Let ZK result is health, but http request is unhealthy. // We expect the check fail if we skipZKRead. String testPartition = "PARTITION_0"; String siblingInstance = "instance0.linkedin.com_1236"; String jsonContent = "{\n" + "\"param1\": \"value1\",\n" + "\"param2\": \"value2\"\n" + "}"; BaseDataAccessor<ZNRecord> mockAccessor = mock(ZkBaseDataAccessor.class); ZKHelixDataAccessor zkHelixDataAccessor = new ZKHelixDataAccessor(TEST_CLUSTER, mockAccessor); ZNRecord successPartitionReport = new ZNRecord(HelixDataAccessorWrapper.PARTITION_HEALTH_KEY); // Instance level check passed when(_customRestClient.getInstanceStoppableCheck(anyString(), anyMap())).thenReturn( Collections.singletonMap(TEST_INSTANCE, true)); // Mocks for partition level when(mockAccessor.getChildNames(zkHelixDataAccessor.keyBuilder().liveInstances().getPath(), 2)).thenReturn( Arrays.asList(TEST_INSTANCE, siblingInstance)); // Mock ZK record is healthy Map<String, String> partition0 = new HashMap<>(); partition0.put(HelixDataAccessorWrapper.EXPIRY_KEY, String.valueOf(System.currentTimeMillis() + 100000L)); partition0.put(HelixDataAccessorWrapper.IS_HEALTHY_KEY, "true"); partition0.put("lastWriteTime", String.valueOf(System.currentTimeMillis())); successPartitionReport.setMapField(testPartition, partition0); when(mockAccessor.get(Arrays.asList(zkHelixDataAccessor.keyBuilder() .healthReport(TEST_INSTANCE, HelixDataAccessorWrapper.PARTITION_HEALTH_KEY) .getPath(), zkHelixDataAccessor.keyBuilder() .healthReport(siblingInstance, HelixDataAccessorWrapper.PARTITION_HEALTH_KEY) .getPath()), Arrays.asList(new Stat(), new Stat()), 0, false)).thenReturn( Arrays.asList(successPartitionReport, successPartitionReport)); // Mock client call result is check fail. when(_customRestClient.getPartitionStoppableCheck(anyString(), anyList(), anyMap())).thenReturn( Collections.singletonMap(testPartition, false)); // Mock data for InstanceValidationUtil ExternalView externalView = new ExternalView("TestResource"); externalView.setState(testPartition, TEST_INSTANCE, "MASTER"); externalView.setState(testPartition, siblingInstance, "SLAVE"); externalView.getRecord().setSimpleField(IdealState.IdealStateProperty.STATE_MODEL_DEF_REF.name(), "MasterSlave"); when(mockAccessor.getChildren(zkHelixDataAccessor.keyBuilder().externalViews().getPath(), null, AccessOption.PERSISTENT, 1, 0)).thenReturn(Arrays.asList(externalView.getRecord())); when(mockAccessor.get(zkHelixDataAccessor.keyBuilder().stateModelDef("MasterSlave").getPath(), new Stat(), AccessOption.PERSISTENT)).thenReturn(MasterSlaveSMD.build().getRecord()); // Valid data only from ZK, pass the check MockMaintenanceManagementService instanceServiceReadZK = new MockMaintenanceManagementService(zkHelixDataAccessor, _configAccessor, _customRestClient, false, false, HelixRestNamespace.DEFAULT_NAMESPACE_NAME); StoppableCheck stoppableCheck = instanceServiceReadZK.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, jsonContent); Assert.assertTrue(stoppableCheck.isStoppable()); // Even ZK data is valid. Skip ZK read should fail the test. MockMaintenanceManagementService instanceServiceWithoutReadZK = new MockMaintenanceManagementService(zkHelixDataAccessor, _configAccessor, _customRestClient, true, false, HelixRestNamespace.DEFAULT_NAMESPACE_NAME); stoppableCheck = instanceServiceWithoutReadZK.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, jsonContent); Assert.assertFalse(stoppableCheck.isStoppable()); // Test take instance with same setting. MaintenanceManagementInstanceInfo instanceInfo = instanceServiceWithoutReadZK.takeInstance(TEST_CLUSTER, TEST_INSTANCE, Collections.singletonList("CustomInstanceStoppableCheck"), MaintenanceManagementService.getMapFromJsonPayload(jsonContent), Collections.singletonList("org.apache.helix.rest.server.TestOperationImpl"), Collections.EMPTY_MAP, true); Assert.assertFalse(instanceInfo.isSuccessful()); Assert.assertEquals(instanceInfo.getMessages().get(0), "CUSTOM_PARTITION_HEALTH_FAILURE:HOST_NO_STATE_ERROR:INSTANCE0.LINKEDIN.COM_1236:PARTITION_0"); // Operation should finish even with check failed. MockMaintenanceManagementService instanceServiceSkipFailure = new MockMaintenanceManagementService(zkHelixDataAccessor, _configAccessor, _customRestClient, true, ImmutableSet.of("CUSTOM_PARTITION_HEALTH_FAILURE:HOST_NO_STATE_ERROR"), HelixRestNamespace.DEFAULT_NAMESPACE_NAME); MaintenanceManagementInstanceInfo instanceInfo2 = instanceServiceSkipFailure.takeInstance(TEST_CLUSTER, TEST_INSTANCE, Collections.singletonList("CustomInstanceStoppableCheck"), MaintenanceManagementService.getMapFromJsonPayload(jsonContent), Collections.singletonList("org.apache.helix.rest.server.TestOperationImpl"), Collections.EMPTY_MAP, true); Assert.assertTrue(instanceInfo2.isSuccessful()); Assert.assertEquals(instanceInfo2.getOperationResult(), "DummyTakeOperationResult"); } /* * Tests stoppable check api when all checks query is enabled. After helix own check fails, * the subsequent checks should be performed. */ @Test public void testGetStoppableWithAllChecks() throws IOException { String siblingInstance = "instance0.linkedin.com_1236"; BaseDataAccessor<ZNRecord> mockAccessor = mock(ZkBaseDataAccessor.class); ZKHelixDataAccessor zkHelixDataAccessor = new ZKHelixDataAccessor(TEST_CLUSTER, mockAccessor); when(mockAccessor.getChildNames(zkHelixDataAccessor.keyBuilder().liveInstances().getPath(), 2)) .thenReturn(Arrays.asList(TEST_INSTANCE, siblingInstance)); Map<String, Boolean> instanceHealthFailedCheck = ImmutableMap.of("FailCheck", false); MockMaintenanceManagementService service = new MockMaintenanceManagementService(zkHelixDataAccessor, _configAccessor, _customRestClient, true, true, HelixRestNamespace.DEFAULT_NAMESPACE_NAME) { @Override protected Map<String, Boolean> getInstanceHealthStatus(String clusterId, String instanceName, List<HealthCheck> healthChecks) { return instanceHealthFailedCheck; } }; when(_customRestClient.getInstanceStoppableCheck(anyString(), anyMap())) .thenReturn(ImmutableMap.of("FailCheck", false)); when(_customRestClient.getPartitionStoppableCheck(anyString(), anyList(), anyMap())) .thenReturn(ImmutableMap.of("FailCheck", false)); StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, ""); List<String> expectedFailedChecks = Arrays.asList("HELIX:FailCheck", "CUSTOM_INSTANCE_HEALTH_FAILURE:FailCheck"); Assert.assertEquals(actual.getFailedChecks(), expectedFailedChecks); Assert.assertFalse(actual.isStoppable()); // Verify the subsequent checks are called verify(_configAccessor, times(1)).getRESTConfig(anyString()); verify(_customRestClient, times(1)).getInstanceStoppableCheck(anyString(), anyMap()); verify(_customRestClient, times(2)) .getPartitionStoppableCheck(anyString(), nullable(List.class), anyMap()); } // TODO re-enable the test when partition health checks get decoupled @Test(enabled = false) public void testGetInstanceStoppableCheckWhenPartitionsCheckFail() throws IOException { MockMaintenanceManagementService service = new MockMaintenanceManagementService(_dataAccessorWrapper, _configAccessor, _customRestClient, false, false, HelixRestNamespace.DEFAULT_NAMESPACE_NAME) { @Override protected Map<String, Boolean> getInstanceHealthStatus(String clusterId, String instanceName, List<HealthCheck> healthChecks) { return Collections.emptyMap(); } }; // partition is health on the test instance but unhealthy on the sibling instance when(_customRestClient.getInstanceStoppableCheck(anyString(), anyMap())) .thenReturn(Collections.emptyMap()); String jsonContent = "{\n" + " \"param1\": \"value1\",\n" + "\"param2\": \"value2\"\n" + "}"; StoppableCheck actual = service.getInstanceStoppableCheck(TEST_CLUSTER, TEST_INSTANCE, jsonContent); Assert.assertFalse(actual.isStoppable()); verify(_customRestClient, times(1)).getInstanceStoppableCheck(any(), any()); } }
9,292
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/metadatastore/TestZkMetadataStoreDirectory.java
package org.apache.helix.rest.metadatastore; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.helix.TestHelper; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; import org.apache.helix.rest.server.AbstractTestClass; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.apache.helix.zookeeper.zkclient.ZkClient; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestZkMetadataStoreDirectory extends AbstractTestClass { /** * The following are constants to be used for testing. */ private static final String TEST_REALM_1 = "testRealm1"; private static final List<String> TEST_SHARDING_KEYS_1 = Arrays.asList("/sharding/key/1/a", "/sharding/key/1/b", "/sharding/key/1/c"); private static final String TEST_REALM_2 = "testRealm2"; private static final List<String> TEST_SHARDING_KEYS_2 = Arrays.asList("/sharding/key/1/d", "/sharding/key/1/e", "/sharding/key/1/f"); private static final String TEST_REALM_3 = "testRealm3"; private static final List<String> TEST_SHARDING_KEYS_3 = Arrays.asList("/sharding/key/1/x", "/sharding/key/1/y", "/sharding/key/1/z"); // List of all ZK addresses, each of which corresponds to a namespace/routing ZK private List<String> _zkList; // <Namespace, ZkAddr> mapping private Map<String, String> _routingZkAddrMap; private MetadataStoreDirectory _metadataStoreDirectory; @BeforeClass public void beforeClass() throws Exception { _zkList = new ArrayList<>(ZK_SERVER_MAP.keySet()); clearRoutingData(); // Populate routingZkAddrMap _routingZkAddrMap = new LinkedHashMap<>(); int namespaceIndex = 0; String namespacePrefix = "namespace_"; for (String zk : _zkList) { _routingZkAddrMap.put(namespacePrefix + namespaceIndex, zk); } // Write dummy mappings in ZK // Create a node that represents a realm address and add 3 sharding keys to it ZNRecord znRecord = new ZNRecord("RoutingInfo"); _zkList.forEach(zk -> { ZK_SERVER_MAP.get(zk).getZkClient().setZkSerializer(new ZNRecordSerializer()); // Write first realm and sharding keys pair znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, TEST_SHARDING_KEYS_1); ZK_SERVER_MAP.get(zk).getZkClient() .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_1, true); ZK_SERVER_MAP.get(zk).getZkClient() .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_1, znRecord); // Create another realm and sharding keys pair znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, TEST_SHARDING_KEYS_2); ZK_SERVER_MAP.get(zk).getZkClient() .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_2, true); ZK_SERVER_MAP.get(zk).getZkClient() .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_2, znRecord); }); System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY, getBaseUri().getHost()); System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY, Integer.toString(getBaseUri().getPort())); // Create metadataStoreDirectory for (Map.Entry<String, String> entry : _routingZkAddrMap.entrySet()) { _metadataStoreDirectory = ZkMetadataStoreDirectory.getInstance(entry.getKey(), entry.getValue()); } } @AfterClass public void afterClass() throws Exception { _metadataStoreDirectory.close(); clearRoutingData(); System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY); System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY); } @Test public void testGetAllNamespaces() { Assert.assertTrue( _metadataStoreDirectory.getAllNamespaces().containsAll(_routingZkAddrMap.keySet())); } @Test(dependsOnMethods = "testGetAllNamespaces") public void testGetAllMetadataStoreRealms() { Set<String> realms = new HashSet<>(); realms.add(TEST_REALM_1); realms.add(TEST_REALM_2); for (String namespace : _routingZkAddrMap.keySet()) { Assert.assertEquals(_metadataStoreDirectory.getAllMetadataStoreRealms(namespace), realms); } } @Test(dependsOnMethods = "testGetAllMetadataStoreRealms") public void testGetAllShardingKeys() { Set<String> allShardingKeys = new HashSet<>(); allShardingKeys.addAll(TEST_SHARDING_KEYS_1); allShardingKeys.addAll(TEST_SHARDING_KEYS_2); for (String namespace : _routingZkAddrMap.keySet()) { Assert.assertEquals(_metadataStoreDirectory.getAllShardingKeys(namespace), allShardingKeys); } } @Test(dependsOnMethods = "testGetAllShardingKeys") public void testGetNamespaceRoutingData() { Map<String, List<String>> routingDataMap = new HashMap<>(); routingDataMap.put(TEST_REALM_1, TEST_SHARDING_KEYS_1); routingDataMap.put(TEST_REALM_2, TEST_SHARDING_KEYS_2); for (String namespace : _routingZkAddrMap.keySet()) { Assert .assertEquals(_metadataStoreDirectory.getNamespaceRoutingData(namespace), routingDataMap); } } @Test(dependsOnMethods = "testGetNamespaceRoutingData") public void testSetNamespaceRoutingData() { Map<String, List<String>> routingDataMap = new HashMap<>(); routingDataMap.put(TEST_REALM_1, TEST_SHARDING_KEYS_2); routingDataMap.put(TEST_REALM_2, TEST_SHARDING_KEYS_1); for (String namespace : _routingZkAddrMap.keySet()) { Assert.assertTrue(_metadataStoreDirectory.setNamespaceRoutingData(namespace, routingDataMap)); Assert .assertEquals(_metadataStoreDirectory.getNamespaceRoutingData(namespace), routingDataMap); } // Revert it back to the original state Map<String, List<String>> originalRoutingDataMap = new HashMap<>(); originalRoutingDataMap.put(TEST_REALM_1, TEST_SHARDING_KEYS_1); originalRoutingDataMap.put(TEST_REALM_2, TEST_SHARDING_KEYS_2); for (String namespace : _routingZkAddrMap.keySet()) { Assert.assertTrue( _metadataStoreDirectory.setNamespaceRoutingData(namespace, originalRoutingDataMap)); Assert.assertEquals(_metadataStoreDirectory.getNamespaceRoutingData(namespace), originalRoutingDataMap); } } @Test(dependsOnMethods = "testGetNamespaceRoutingData") public void testGetAllShardingKeysInRealm() { for (String namespace : _routingZkAddrMap.keySet()) { // Test two realms independently Assert .assertEquals(_metadataStoreDirectory.getAllShardingKeysInRealm(namespace, TEST_REALM_1), TEST_SHARDING_KEYS_1); Assert .assertEquals(_metadataStoreDirectory.getAllShardingKeysInRealm(namespace, TEST_REALM_2), TEST_SHARDING_KEYS_2); } } @Test(dependsOnMethods = "testGetAllShardingKeysInRealm") public void testGetAllMappingUnderPath() { Map<String, String> mappingFromRoot = new HashMap<>(); TEST_SHARDING_KEYS_1.forEach(shardingKey -> { mappingFromRoot.put(shardingKey, TEST_REALM_1); }); TEST_SHARDING_KEYS_2.forEach(shardingKey -> { mappingFromRoot.put(shardingKey, TEST_REALM_2); }); Map<String, String> mappingFromLeaf = new HashMap<>(1); mappingFromLeaf.put("/sharding/key/1/a", TEST_REALM_1); for (String namespace : _routingZkAddrMap.keySet()) { Assert.assertEquals(_metadataStoreDirectory.getAllMappingUnderPath(namespace, "/"), mappingFromRoot); Assert.assertEquals( _metadataStoreDirectory.getAllMappingUnderPath(namespace, "/sharding/key/1/a"), mappingFromLeaf); } } @Test(dependsOnMethods = "testGetAllMappingUnderPath") public void testGetMetadataStoreRealm() { for (String namespace : _routingZkAddrMap.keySet()) { Assert.assertEquals( _metadataStoreDirectory.getMetadataStoreRealm(namespace, "/sharding/key/1/a/x/y/z"), TEST_REALM_1); Assert.assertEquals( _metadataStoreDirectory.getMetadataStoreRealm(namespace, "/sharding/key/1/d/x/y/z"), TEST_REALM_2); } } @Test(dependsOnMethods = "testGetMetadataStoreRealm") public void testDataChangeCallback() throws Exception { // For all namespaces (Routing ZKs), add an extra sharding key to TEST_REALM_1 String newKey = "/a/b/c/d/e"; _zkList.forEach(zk -> { ZNRecord znRecord = ZK_SERVER_MAP.get(zk).getZkClient() .readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_1); znRecord.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY).add(newKey); ZK_SERVER_MAP.get(zk).getZkClient() .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_1, znRecord); }); // Verify that the sharding keys field have been updated Assert.assertTrue(TestHelper.verify(() -> { for (String namespace : _routingZkAddrMap.keySet()) { try { return _metadataStoreDirectory.getAllShardingKeys(namespace).contains(newKey) && _metadataStoreDirectory.getAllShardingKeysInRealm(namespace, TEST_REALM_1) .contains(newKey); } catch (NoSuchElementException e) { // Pass - wait until callback is called } } return false; }, TestHelper.WAIT_DURATION)); } @Test(dependsOnMethods = "testDataChangeCallback") public void testChildChangeCallback() throws Exception { // For all namespaces (Routing ZKs), add a realm with a sharding key list _zkList.forEach(zk -> { ZK_SERVER_MAP.get(zk).getZkClient() .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_3, true); ZNRecord znRecord = new ZNRecord("RoutingInfo"); znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, TEST_SHARDING_KEYS_3); ZK_SERVER_MAP.get(zk).getZkClient() .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_3, znRecord); }); // Verify that the new realm and sharding keys have been updated in-memory via callback Assert.assertTrue(TestHelper.verify(() -> { for (String namespace : _routingZkAddrMap.keySet()) { try { return _metadataStoreDirectory.getAllMetadataStoreRealms(namespace).contains(TEST_REALM_3) && _metadataStoreDirectory.getAllShardingKeysInRealm(namespace, TEST_REALM_3) .containsAll(TEST_SHARDING_KEYS_3); } catch (NoSuchElementException e) { // Pass - wait until callback is called } } return false; }, TestHelper.WAIT_DURATION)); // Since there was a child change callback, make sure data change works on the new child (realm) as well by adding a key // This tests removing all subscriptions and subscribing with new children list // For all namespaces (Routing ZKs), add an extra sharding key to TEST_REALM_3 String newKey = "/x/y/z"; _zkList.forEach(zk -> { ZNRecord znRecord = ZK_SERVER_MAP.get(zk).getZkClient() .readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_3); znRecord.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY).add(newKey); ZK_SERVER_MAP.get(zk).getZkClient() .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + TEST_REALM_3, znRecord); }); // Verify that the sharding keys field have been updated Assert.assertTrue(TestHelper.verify(() -> { for (String namespace : _routingZkAddrMap.keySet()) { try { return _metadataStoreDirectory.getAllShardingKeys(namespace).contains(newKey) && _metadataStoreDirectory.getAllShardingKeysInRealm(namespace, TEST_REALM_3) .contains(newKey); } catch (NoSuchElementException e) { // Pass - wait until callback is called } } return false; }, TestHelper.WAIT_DURATION)); } @Test(dependsOnMethods = "testChildChangeCallback") public void testDataDeletionCallback() throws Exception { // For all namespaces, delete all routing data _zkList.forEach(zk -> { ZkClient zkClient = ZK_SERVER_MAP.get(zk).getZkClient(); if (zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { for (String zkRealm : zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } } } ); // Confirm that TrieRoutingData has been removed due to missing routing data Assert.assertTrue(TestHelper.verify(() -> { for (String namespace : _routingZkAddrMap.keySet()) { try { _metadataStoreDirectory.getMetadataStoreRealm(namespace, TEST_SHARDING_KEYS_1.get(0)); // Metadata store realm is not yet refreshed. Retry. return false; } catch (IllegalStateException e) { // If other IllegalStateException, it is unexpected and this test should fail. if (!e.getMessage().equals("Failed to get metadata store realm: Namespace " + namespace + " contains either empty or invalid routing data!")) { throw e; } } } return true; }, TestHelper.WAIT_DURATION)); } private void clearRoutingData() throws Exception { Assert.assertTrue(TestHelper.verify(() -> { for (String zk : _zkList) { ZkClient zkClient = ZK_SERVER_MAP.get(zk).getZkClient(); if (zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { for (String zkRealm : zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } } } for (String zk : _zkList) { ZkClient zkClient = ZK_SERVER_MAP.get(zk).getZkClient(); if (zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH) && !zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH).isEmpty()) { return false; } } return true; }, TestHelper.WAIT_DURATION), "Routing data path should be deleted after the tests."); } }
9,293
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/metadatastore
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/metadatastore/accessor/TestZkRoutingDataWriter.java
package org.apache.helix.rest.metadatastore.accessor; /* * 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.Map; import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.rest.common.HttpConstants; import org.apache.helix.rest.server.AbstractTestClass; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.http.client.methods.HttpUriRequest; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestZkRoutingDataWriter extends AbstractTestClass { private static final String DUMMY_REALM = "REALM"; private static final String DUMMY_SHARDING_KEY = "/DUMMY/SHARDING/KEY"; private MetadataStoreRoutingDataWriter _zkRoutingDataWriter; // MockWriter is used for testing request forwarding features in non-leader situations class MockWriter extends ZkRoutingDataWriter { HttpUriRequest calledRequest; MockWriter(String namespace, String zkAddress) { super(namespace, zkAddress); } // This method does not call super() because the http call should not be actually made @Override protected boolean sendRequestToLeader(HttpUriRequest request, int expectedResponseCode) { calledRequest = request; return false; } } @BeforeClass public void beforeClass() throws Exception { System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY, getBaseUri().getHost()); System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY, Integer.toString(getBaseUri().getPort())); _zkRoutingDataWriter = new ZkRoutingDataWriter(TEST_NAMESPACE, _zkAddrTestNS); clearRoutingDataPath(); } @AfterClass public void afterClass() throws Exception { System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY); System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY); _zkRoutingDataWriter.close(); clearRoutingDataPath(); } @Test public void testAddMetadataStoreRealm() { _zkRoutingDataWriter.addMetadataStoreRealm(DUMMY_REALM); ZNRecord znRecord = _gZkClientTestNS .readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + DUMMY_REALM); Assert.assertNotNull(znRecord); } @Test(dependsOnMethods = "testAddMetadataStoreRealm") public void testDeleteMetadataStoreRealm() { _zkRoutingDataWriter.deleteMetadataStoreRealm(DUMMY_REALM); Assert.assertFalse(_gZkClientTestNS .exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + DUMMY_REALM)); } @Test(dependsOnMethods = "testDeleteMetadataStoreRealm") public void testAddShardingKey() { _zkRoutingDataWriter.addShardingKey(DUMMY_REALM, DUMMY_SHARDING_KEY); ZNRecord znRecord = _gZkClientTestNS .readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + DUMMY_REALM); Assert.assertNotNull(znRecord); Assert.assertTrue(znRecord.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY) .contains(DUMMY_SHARDING_KEY)); } @Test(dependsOnMethods = "testAddShardingKey") public void testDeleteShardingKey() { _zkRoutingDataWriter.deleteShardingKey(DUMMY_REALM, DUMMY_SHARDING_KEY); ZNRecord znRecord = _gZkClientTestNS .readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + DUMMY_REALM); Assert.assertNotNull(znRecord); Assert.assertFalse(znRecord.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY) .contains(DUMMY_SHARDING_KEY)); } @Test(dependsOnMethods = "testDeleteShardingKey") public void testSetRoutingData() { Map<String, List<String>> testRoutingDataMap = ImmutableMap.of(DUMMY_REALM, Collections.singletonList(DUMMY_SHARDING_KEY)); _zkRoutingDataWriter.setRoutingData(testRoutingDataMap); ZNRecord znRecord = _gZkClientTestNS .readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + DUMMY_REALM); Assert.assertNotNull(znRecord); Assert.assertEquals( znRecord.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY).size(), 1); Assert.assertTrue(znRecord.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY) .contains(DUMMY_SHARDING_KEY)); } @Test(dependsOnMethods = "testSetRoutingData") public void testAddMetadataStoreRealmNonLeader() { MockWriter mockWriter = new MockWriter(TEST_NAMESPACE, _zkAddrTestNS); mockWriter.addMetadataStoreRealm(DUMMY_REALM); Assert.assertEquals(mockWriter.calledRequest.getMethod(), HttpConstants.RestVerbs.PUT.name()); List<String> expectedUrlParams = Arrays .asList(MetadataStoreRoutingConstants.MSDS_NAMESPACES_URL_PREFIX, TEST_NAMESPACE, MetadataStoreRoutingConstants.MSDS_GET_ALL_REALMS_ENDPOINT, DUMMY_REALM); String expectedUrl = getBaseUri().toString() + String.join("/", expectedUrlParams).replaceAll("//", "/") .substring(1); Assert.assertEquals(mockWriter.calledRequest.getURI().toString(), expectedUrl); mockWriter.close(); } @Test(dependsOnMethods = "testAddMetadataStoreRealmNonLeader") public void testDeleteMetadataStoreRealmNonLeader() { MockWriter mockWriter = new MockWriter(TEST_NAMESPACE, _zkAddrTestNS); mockWriter.deleteMetadataStoreRealm(DUMMY_REALM); Assert .assertEquals(mockWriter.calledRequest.getMethod(), HttpConstants.RestVerbs.DELETE.name()); List<String> expectedUrlParams = Arrays .asList(MetadataStoreRoutingConstants.MSDS_NAMESPACES_URL_PREFIX, TEST_NAMESPACE, MetadataStoreRoutingConstants.MSDS_GET_ALL_REALMS_ENDPOINT, DUMMY_REALM); String expectedUrl = getBaseUri().toString() + String.join("/", expectedUrlParams).replaceAll("//", "/") .substring(1); Assert.assertEquals(mockWriter.calledRequest.getURI().toString(), expectedUrl); mockWriter.close(); } @Test(dependsOnMethods = "testDeleteMetadataStoreRealmNonLeader") public void testAddShardingKeyNonLeader() { MockWriter mockWriter = new MockWriter(TEST_NAMESPACE, _zkAddrTestNS); mockWriter.addShardingKey(DUMMY_REALM, DUMMY_SHARDING_KEY); Assert.assertEquals(mockWriter.calledRequest.getMethod(), HttpConstants.RestVerbs.PUT.name()); List<String> expectedUrlParams = Arrays .asList(MetadataStoreRoutingConstants.MSDS_NAMESPACES_URL_PREFIX, TEST_NAMESPACE, MetadataStoreRoutingConstants.MSDS_GET_ALL_REALMS_ENDPOINT, DUMMY_REALM, MetadataStoreRoutingConstants.MSDS_GET_ALL_SHARDING_KEYS_ENDPOINT, DUMMY_SHARDING_KEY); String expectedUrl = getBaseUri().toString() + String.join("/", expectedUrlParams).replaceAll("//", "/") .substring(1); Assert.assertEquals(mockWriter.calledRequest.getURI().toString(), expectedUrl); mockWriter.close(); } @Test(dependsOnMethods = "testAddShardingKeyNonLeader") public void testDeleteShardingKeyNonLeader() { MockWriter mockWriter = new MockWriter(TEST_NAMESPACE, _zkAddrTestNS); mockWriter.deleteShardingKey(DUMMY_REALM, DUMMY_SHARDING_KEY); Assert .assertEquals(mockWriter.calledRequest.getMethod(), HttpConstants.RestVerbs.DELETE.name()); List<String> expectedUrlParams = Arrays .asList(MetadataStoreRoutingConstants.MSDS_NAMESPACES_URL_PREFIX, TEST_NAMESPACE, MetadataStoreRoutingConstants.MSDS_GET_ALL_REALMS_ENDPOINT, DUMMY_REALM, MetadataStoreRoutingConstants.MSDS_GET_ALL_SHARDING_KEYS_ENDPOINT, DUMMY_SHARDING_KEY); String expectedUrl = getBaseUri().toString() + String.join("/", expectedUrlParams).replaceAll("//", "/") .substring(1); Assert.assertEquals(mockWriter.calledRequest.getURI().toString(), expectedUrl); mockWriter.close(); } @Test(dependsOnMethods = "testDeleteShardingKeyNonLeader") public void testSetRoutingDataNonLeader() { MockWriter mockWriter = new MockWriter(TEST_NAMESPACE, _zkAddrTestNS); Map<String, List<String>> testRoutingDataMap = ImmutableMap.of(DUMMY_REALM, Collections.singletonList(DUMMY_SHARDING_KEY)); mockWriter.setRoutingData(testRoutingDataMap); Assert.assertEquals(mockWriter.calledRequest.getMethod(), HttpConstants.RestVerbs.PUT.name()); List<String> expectedUrlParams = Arrays .asList(MetadataStoreRoutingConstants.MSDS_NAMESPACES_URL_PREFIX, TEST_NAMESPACE, MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT); String expectedUrl = getBaseUri().toString() + String.join("/", expectedUrlParams).replaceAll("//", "/") .substring(1); Assert.assertEquals(mockWriter.calledRequest.getURI().toString(), expectedUrl); mockWriter.close(); } private void clearRoutingDataPath() throws Exception { Assert.assertTrue(TestHelper.verify(() -> { for (String zkRealm : _gZkClientTestNS .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { _gZkClientTestNS.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } return _gZkClientTestNS.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH) .isEmpty(); }, TestHelper.WAIT_DURATION), "Routing data path should be deleted after the tests."); } }
9,294
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/metadatastore
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/metadatastore/accessor/TestZkRoutingDataReader.java
package org.apache.helix.rest.metadatastore.accessor; /* * 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.Map; import org.apache.helix.TestHelper; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; import org.apache.helix.rest.server.AbstractTestClass; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestZkRoutingDataReader extends AbstractTestClass { private MetadataStoreRoutingDataReader _zkRoutingDataReader; @BeforeClass public void beforeClass() throws Exception { _zkRoutingDataReader = new ZkRoutingDataReader(TEST_NAMESPACE, _zkAddrTestNS, null); clearRoutingDataPath(); } @AfterClass public void afterClass() throws Exception { _zkRoutingDataReader.close(); clearRoutingDataPath(); } @AfterMethod public void afterMethod() throws Exception { clearRoutingDataPath(); } @Test public void testGetRoutingData() { // Create a node that represents a realm address and add 3 sharding keys to it ZNRecord testZnRecord1 = new ZNRecord("testZnRecord1"); List<String> testShardingKeys1 = Arrays.asList("/sharding/key/1/a", "/sharding/key/1/b", "/sharding/key/1/c"); testZnRecord1 .setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, testShardingKeys1); // Create another node that represents a realm address and add 3 sharding keys to it ZNRecord testZnRecord2 = new ZNRecord("testZnRecord2"); List<String> testShardingKeys2 = Arrays .asList("/sharding/key/2/a", "/sharding/key/2/b", "/sharding/key/2/c", "/sharding/key/2/d"); testZnRecord2 .setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, testShardingKeys2); // Add both nodes as children nodes to ZkRoutingDataReader.ROUTING_DATA_PATH _gZkClientTestNS .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/testRealmAddress1", testZnRecord1); _gZkClientTestNS .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/testRealmAddress2", testZnRecord2); try { Map<String, List<String>> routingData = _zkRoutingDataReader.getRoutingData(); Assert.assertEquals(routingData.size(), 2); Assert.assertEquals(routingData.get("testRealmAddress1"), testShardingKeys1); Assert.assertEquals(routingData.get("testRealmAddress2"), testShardingKeys2); } catch (InvalidRoutingDataException e) { Assert.fail("Not expecting InvalidRoutingDataException"); } } @Test(dependsOnMethods = "testGetRoutingData") public void testGetRoutingDataMissingMSRDChildren() { try { Map<String, List<String>> routingData = _zkRoutingDataReader.getRoutingData(); Assert.assertEquals(routingData.size(), 0); } catch (InvalidRoutingDataException e) { Assert.fail("Not expecting InvalidRoutingDataException"); } } @Test(dependsOnMethods = "testGetRoutingData") public void testGetRoutingDataMSRDChildEmptyValue() { ZNRecord testZnRecord1 = new ZNRecord("testZnRecord1"); testZnRecord1.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, Collections.emptyList()); _gZkClientTestNS .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/testRealmAddress1", testZnRecord1); try { Map<String, List<String>> routingData = _zkRoutingDataReader.getRoutingData(); Assert.assertEquals(routingData.size(), 1); Assert.assertTrue(routingData.get("testRealmAddress1").isEmpty()); } catch (InvalidRoutingDataException e) { Assert.fail("Not expecting InvalidRoutingDataException"); } } private void clearRoutingDataPath() throws Exception { Assert.assertTrue(TestHelper.verify(() -> { for (String zkRealm : _gZkClientTestNS .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { _gZkClientTestNS.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } return _gZkClientTestNS.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH).isEmpty(); }, TestHelper.WAIT_DURATION), "Routing data path should be deleted after the tests."); } }
9,295
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/metadatastore
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/metadatastore/integration/TestRoutingDataUpdate.java
package org.apache.helix.rest.metadatastore.integration; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.helix.SystemPropertyKeys; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.rest.server.AbstractTestClass; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * TestRoutingDataUpdate tests that Helix REST server's ServerContext gets a proper update whenever * there is change in the routing data. */ public class TestRoutingDataUpdate extends AbstractTestClass { private static final String CLUSTER_0_SHARDING_KEY = "/TestRoutingDataUpdate-cluster-0"; private static final String CLUSTER_1_SHARDING_KEY = "/TestRoutingDataUpdate-cluster-1"; private final Map<String, List<String>> _routingData = new HashMap<>(); @BeforeClass public void beforeClass() { System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY, getBaseUri().getHost()); System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY, Integer.toString(getBaseUri().getPort())); // Set the multi-zk config System.setProperty(SystemPropertyKeys.MULTI_ZK_ENABLED, "true"); // Set the MSDS address String msdsEndpoint = getBaseUri().toString(); System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY, msdsEndpoint); // Restart Helix Rest server to get a fresh ServerContext created restartRestServer(); } @AfterClass public void afterClass() { // Clear all property System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY); System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY); System.clearProperty(SystemPropertyKeys.MULTI_ZK_ENABLED); restartRestServer(); } @Test public void testRoutingDataUpdate() throws Exception { // Set up routing data _routingData.put(ZK_ADDR, Arrays.asList(CLUSTER_0_SHARDING_KEY, CLUSTER_1_SHARDING_KEY)); _routingData.put(_zkAddrTestNS, new ArrayList<>()); String routingDataString = OBJECT_MAPPER.writeValueAsString(_routingData); put(MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT, null, Entity.entity(routingDataString, MediaType.APPLICATION_JSON_TYPE), Response.Status.CREATED.getStatusCode()); // Need to wait so that ServerContext processes the callback // TODO: Think of another way to wait - // this is only used because of the nature of the testing environment // in production, the server might return a 500 if a http call comes in before callbacks get // processed fully Thread.sleep(500L); // Create the first cluster using Helix REST API via ClusterAccessor put("/clusters" + CLUSTER_0_SHARDING_KEY, null, Entity.entity("", MediaType.APPLICATION_JSON_TYPE), Response.Status.CREATED.getStatusCode()); // Check that the first cluster is created in the first ZK as designated by routing data Assert.assertTrue(_gZkClient.exists(CLUSTER_0_SHARDING_KEY)); Assert.assertFalse(_gZkClientTestNS.exists(CLUSTER_0_SHARDING_KEY)); // Change the routing data mapping so that CLUSTER_1 points to the second ZK _routingData.clear(); _routingData.put(ZK_ADDR, Collections.singletonList(CLUSTER_0_SHARDING_KEY)); _routingData.put(_zkAddrTestNS, Collections.singletonList(CLUSTER_1_SHARDING_KEY)); routingDataString = OBJECT_MAPPER.writeValueAsString(_routingData); put(MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT, null, Entity.entity(routingDataString, MediaType.APPLICATION_JSON_TYPE), Response.Status.CREATED.getStatusCode()); // Need to wait so that ServerContext processes the callback // TODO: Think of another way to wait - // this is only used because of the nature of the testing environment // in production, the server might return a 500 if a http call comes in before callbacks get // processed fully Thread.sleep(500L); // Create the second cluster using Helix REST API via ClusterAccessor put("/clusters" + CLUSTER_1_SHARDING_KEY, null, Entity.entity("", MediaType.APPLICATION_JSON_TYPE), Response.Status.CREATED.getStatusCode()); // Check that the second cluster is created in the second ZK as designated by routing data Assert.assertTrue(_gZkClientTestNS.exists(CLUSTER_1_SHARDING_KEY)); Assert.assertFalse(_gZkClient.exists(CLUSTER_1_SHARDING_KEY)); // Remove all routing data put(MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT, null, Entity .entity(OBJECT_MAPPER.writeValueAsString(Collections.emptyMap()), MediaType.APPLICATION_JSON_TYPE), Response.Status.CREATED.getStatusCode()); // Need to wait so that ServerContext processes the callback // TODO: Think of another way to wait - // this is only used because of the nature of the testing environment // in production, the server might return a 500 if a http call comes in before callbacks get // processed fully Thread.sleep(500L); // Delete clusters - both should fail because routing data don't have these clusters delete("/clusters" + CLUSTER_0_SHARDING_KEY, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); delete("/clusters" + CLUSTER_1_SHARDING_KEY, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // Set the routing data again put(MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT, null, Entity.entity(routingDataString, MediaType.APPLICATION_JSON_TYPE), Response.Status.CREATED.getStatusCode()); // Need to wait so that ServerContext processes the callback // TODO: Think of another way to wait - // this is only used because of the nature of the testing environment // in production, the server might return a 500 if a http call comes in before callbacks get // processed fully Thread.sleep(500L); // Attempt deletion again - now they should succeed delete("/clusters" + CLUSTER_0_SHARDING_KEY, Response.Status.OK.getStatusCode()); delete("/clusters" + CLUSTER_1_SHARDING_KEY, Response.Status.OK.getStatusCode()); // Double-verify using ZkClients Assert.assertFalse(_gZkClientTestNS.exists(CLUSTER_1_SHARDING_KEY)); Assert.assertFalse(_gZkClient.exists(CLUSTER_0_SHARDING_KEY)); // Remove all routing data put(MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT, null, Entity .entity(OBJECT_MAPPER.writeValueAsString(Collections.emptyMap()), MediaType.APPLICATION_JSON_TYPE), Response.Status.CREATED.getStatusCode()); } private void restartRestServer() { if (_helixRestServer != null) { _helixRestServer.shutdown(); } _helixRestServer = startRestServer(); } }
9,296
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/server/TestMSDAccessorLeaderElection.java
package org.apache.helix.rest.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.core.Response; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; import org.apache.helix.rest.common.ContextPropertyKeys; import org.apache.helix.rest.common.HelixRestNamespace; import org.apache.helix.rest.common.HttpConstants; import org.apache.helix.rest.common.ServletType; import org.apache.helix.rest.metadatastore.accessor.ZkRoutingDataWriter; import org.apache.helix.rest.server.auditlog.AuditLogger; import org.apache.helix.rest.server.filters.CORSFilter; import org.apache.helix.rest.server.mock.MockMetadataStoreDirectoryAccessor; import org.apache.helix.zookeeper.api.client.HelixZkClient; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.glassfish.jersey.server.ResourceConfig; 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 TestMSDAccessorLeaderElection extends MetadataStoreDirectoryAccessorTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestMSDAccessorLeaderElection.class); private static final String MOCK_URL_PREFIX = "/mock"; private HelixRestServer _mockHelixRestServer; private String _mockBaseUri; private String _leaderBaseUri; private CloseableHttpClient _httpClient; private HelixZkClient _zkClient; @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); _leaderBaseUri = getBaseUri().toString(); _leaderBaseUri = _leaderBaseUri.substring(0, _leaderBaseUri.length() - 1); int newPort = getBaseUri().getPort() + 1; // Start a second server for testing Distributed Leader Election for writes _mockBaseUri = HttpConstants.HTTP_PROTOCOL_PREFIX + getBaseUri().getHost() + ":" + newPort; try { List<HelixRestNamespace> namespaces = new ArrayList<>(); // Add test namespace namespaces.add(new HelixRestNamespace(TEST_NAMESPACE, HelixRestNamespace.HelixMetadataStoreType.ZOOKEEPER, _zkAddrTestNS, false)); _mockHelixRestServer = new MockHelixRestServer(namespaces, newPort, getBaseUri().getPath(), Collections.singletonList(_auditLogger)); _mockHelixRestServer.start(); } catch (InterruptedException e) { LOG.error("MockHelixRestServer starting encounter an exception.", e); } // Calling the original endpoint to create an instance of MetadataStoreDirectory in case // it didn't exist yet. get(TEST_NAMESPACE_URI_PREFIX + "/metadata-store-realms", null, Response.Status.OK.getStatusCode(), true); // Set the new uri to be used in leader election System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_HOSTNAME_KEY, getBaseUri().getHost()); System .setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_PORT_KEY, Integer.toString(newPort)); // Start http client for testing _httpClient = HttpClients.createDefault(); // Start zkclient to verify leader election behavior _zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(_zkAddrTestNS), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); } @AfterClass public void afterClass() throws Exception { super.afterClass(); MockMetadataStoreDirectoryAccessor._mockMSDInstance.close(); _mockHelixRestServer.shutdown(); _httpClient.close(); _zkClient.close(); } @Test public void testAddMetadataStoreRealmRequestForwarding() throws InvalidRoutingDataException, IOException { Set<String> expectedRealmsSet = getAllRealms(); Assert.assertFalse(expectedRealmsSet.contains(TEST_REALM_3), "Metadata store directory should not have realm: " + TEST_REALM_3); HttpUriRequest request = buildRequest("/metadata-store-realms/" + TEST_REALM_3, HttpConstants.RestVerbs.PUT, ""); sendRequestAndValidate(request, Response.Status.CREATED.getStatusCode()); expectedRealmsSet.add(TEST_REALM_3); Assert.assertEquals(getAllRealms(), expectedRealmsSet); MockMetadataStoreDirectoryAccessor._mockMSDInstance.close(); } @Test(dependsOnMethods = "testAddMetadataStoreRealmRequestForwarding") public void testDeleteMetadataStoreRealmRequestForwarding() throws InvalidRoutingDataException, IOException { Set<String> expectedRealmsSet = getAllRealms(); HttpUriRequest request = buildRequest("/metadata-store-realms/" + TEST_REALM_3, HttpConstants.RestVerbs.DELETE, ""); sendRequestAndValidate(request, Response.Status.OK.getStatusCode()); expectedRealmsSet.remove(TEST_REALM_3); Assert.assertEquals(getAllRealms(), expectedRealmsSet); MockMetadataStoreDirectoryAccessor._mockMSDInstance.close(); } @Test(dependsOnMethods = "testDeleteMetadataStoreRealmRequestForwarding") public void testAddShardingKeyRequestForwarding() throws InvalidRoutingDataException, IOException { Set<String> expectedShardingKeysSet = getAllShardingKeysInTestRealm1(); Assert.assertFalse(expectedShardingKeysSet.contains(TEST_SHARDING_KEY), "Realm does not have sharding key: " + TEST_SHARDING_KEY); HttpUriRequest request = buildRequest( "/metadata-store-realms/" + TEST_REALM_1 + "/sharding-keys/" + TEST_SHARDING_KEY, HttpConstants.RestVerbs.PUT, ""); sendRequestAndValidate(request, Response.Status.CREATED.getStatusCode()); expectedShardingKeysSet.add(TEST_SHARDING_KEY); Assert.assertEquals(getAllShardingKeysInTestRealm1(), expectedShardingKeysSet); MockMetadataStoreDirectoryAccessor._mockMSDInstance.close(); } @Test(dependsOnMethods = "testAddShardingKeyRequestForwarding") public void testDeleteShardingKeyRequestForwarding() throws InvalidRoutingDataException, IOException { Set<String> expectedShardingKeysSet = getAllShardingKeysInTestRealm1(); HttpUriRequest request = buildRequest( "/metadata-store-realms/" + TEST_REALM_1 + "/sharding-keys/" + TEST_SHARDING_KEY, HttpConstants.RestVerbs.DELETE, ""); sendRequestAndValidate(request, Response.Status.OK.getStatusCode()); expectedShardingKeysSet.remove(TEST_SHARDING_KEY); Assert.assertEquals(getAllShardingKeysInTestRealm1(), expectedShardingKeysSet); MockMetadataStoreDirectoryAccessor._mockMSDInstance.close(); } @Test(dependsOnMethods = "testDeleteShardingKeyRequestForwarding") public void testSetRoutingDataRequestForwarding() throws InvalidRoutingDataException, IOException { Map<String, List<String>> routingData = new HashMap<>(); routingData.put(TEST_REALM_1, TEST_SHARDING_KEYS_2); routingData.put(TEST_REALM_2, TEST_SHARDING_KEYS_1); String routingDataString = new ObjectMapper().writeValueAsString(routingData); HttpUriRequest request = buildRequest(MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT, HttpConstants.RestVerbs.PUT, routingDataString); sendRequestAndValidate(request, Response.Status.CREATED.getStatusCode()); Assert.assertEquals(getRawRoutingData(), routingData); MockMetadataStoreDirectoryAccessor._mockMSDInstance.close(); } private HttpUriRequest buildRequest(String urlSuffix, HttpConstants.RestVerbs requestMethod, String jsonEntity) { String url = _mockBaseUri + TEST_NAMESPACE_URI_PREFIX + MOCK_URL_PREFIX + urlSuffix; switch (requestMethod) { case PUT: HttpPut httpPut = new HttpPut(url); httpPut.setEntity(new StringEntity(jsonEntity, ContentType.APPLICATION_JSON)); return httpPut; case DELETE: return new HttpDelete(url); default: throw new IllegalArgumentException("Unsupported requestMethod: " + requestMethod); } } private void sendRequestAndValidate(HttpUriRequest request, int expectedResponseCode) throws IllegalArgumentException, IOException { HttpResponse response = _httpClient.execute(request); Assert.assertEquals(response.getStatusLine().getStatusCode(), expectedResponseCode); // Validate leader election behavior List<String> leaderSelectionNodes = _zkClient.getChildren(MetadataStoreRoutingConstants.LEADER_ELECTION_ZNODE); leaderSelectionNodes.sort(Comparator.comparing(String::toString)); Assert.assertEquals(leaderSelectionNodes.size(), 2); ZNRecord firstEphemeralNode = _zkClient.readData( MetadataStoreRoutingConstants.LEADER_ELECTION_ZNODE + "/" + leaderSelectionNodes.get(0)); ZNRecord secondEphemeralNode = _zkClient.readData( MetadataStoreRoutingConstants.LEADER_ELECTION_ZNODE + "/" + leaderSelectionNodes.get(1)); Assert.assertEquals(ZkRoutingDataWriter.buildEndpointFromLeaderElectionNode(firstEphemeralNode), _leaderBaseUri); Assert .assertEquals(ZkRoutingDataWriter.buildEndpointFromLeaderElectionNode(secondEphemeralNode), _mockBaseUri); // Make sure the operation is not done by the follower instance Assert.assertFalse(MockMetadataStoreDirectoryAccessor.operatedOnZk); } /** * A class that mocks HelixRestServer for testing. It overloads getResourceConfig to inject * MockMetadataStoreDirectoryAccessor as a servlet. */ class MockHelixRestServer extends HelixRestServer { public MockHelixRestServer(List<HelixRestNamespace> namespaces, int port, String urlPrefix, List<AuditLogger> auditLoggers) { super(namespaces, port, urlPrefix, auditLoggers); } public MockHelixRestServer(String zkAddr, int port, String urlPrefix) { super(zkAddr, port, urlPrefix); } @Override protected ResourceConfig getResourceConfig(HelixRestNamespace namespace, ServletType type) { ResourceConfig cfg = new ResourceConfig(); List<String> packages = new ArrayList<>(Arrays.asList(type.getServletPackageArray())); packages.add(MockMetadataStoreDirectoryAccessor.class.getPackage().getName()); cfg.packages(packages.toArray(new String[0])); cfg.setApplicationName(namespace.getName()); cfg.property(ContextPropertyKeys.SERVER_CONTEXT.name(), new ServerContext(namespace.getMetadataStoreAddress())); cfg.property(ContextPropertyKeys.METADATA.name(), namespace); cfg.register(new CORSFilter()); return cfg; } } }
9,297
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/server/TestTaskAccessor.java
package org.apache.helix.rest.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.testng.Assert; import org.testng.annotations.Test; public class TestTaskAccessor extends AbstractTestClass { private final static String CLUSTER_NAME = "TestCluster_0"; @Test public void testGetAddTaskUserContent() throws IOException { System.out.println("Start test :" + TestHelper.getTestMethodName()); String uri = "clusters/" + CLUSTER_NAME + "/workflows/Workflow_0/jobs/JOB0/tasks/0/userContent"; String uriTaskDoesNotExist = "clusters/" + CLUSTER_NAME + "/workflows/Workflow_0/jobs/JOB0/tasks/xxx/userContent"; // Empty user content String body = get(uri, null, Response.Status.OK.getStatusCode(), true); Map<String, String> contentStore = OBJECT_MAPPER.readValue(body, new TypeReference<Map<String, String>>() {}); Assert.assertTrue(contentStore.isEmpty()); // Post user content Map<String, String> map1 = new HashMap<>(); map1.put("k1", "v1"); Entity entity = Entity.entity(OBJECT_MAPPER.writeValueAsString(map1), MediaType.APPLICATION_JSON_TYPE); post(uri, ImmutableMap.of("command", "update"), entity, Response.Status.OK.getStatusCode()); post(uriTaskDoesNotExist, ImmutableMap.of("command", "update"), entity, Response.Status.OK.getStatusCode()); // get after post should work body = get(uri, null, Response.Status.OK.getStatusCode(), true); contentStore = OBJECT_MAPPER.readValue(body, new TypeReference<Map<String, String>>() { }); Assert.assertEquals(contentStore, map1); body = get(uriTaskDoesNotExist, null, Response.Status.OK.getStatusCode(), true); contentStore = OBJECT_MAPPER.readValue(body, new TypeReference<Map<String, String>>() { }); Assert.assertEquals(contentStore, map1); // modify map1 and verify map1.put("k1", "v2"); map1.put("k2", "v2"); entity = Entity.entity(OBJECT_MAPPER.writeValueAsString(map1), MediaType.APPLICATION_JSON_TYPE); post(uri, ImmutableMap.of("command", "update"), entity, Response.Status.OK.getStatusCode()); body = get(uri, null, Response.Status.OK.getStatusCode(), true); contentStore = OBJECT_MAPPER.readValue(body, new TypeReference<Map<String, String>>() { }); Assert.assertEquals(contentStore, map1); System.out.println("End test :" + TestHelper.getTestMethodName()); } @Test(dependsOnMethods = "testGetAddTaskUserContent") public void testInvalidGetAddTaskUserContent() { System.out.println("Start test :" + TestHelper.getTestMethodName()); String validURI = "clusters/" + CLUSTER_NAME + "/workflows/Workflow_0/jobs/Job_0/tasks/0/userContent"; String invalidURI1 = "clusters/" + CLUSTER_NAME + "/workflows/xxx/jobs/Job_0/tasks/0/userContent"; // workflow not exist String invalidURI2 = "clusters/" + CLUSTER_NAME + "/workflows/Workflow_0/jobs/xxx/tasks/0/userContent"; // job not exist String invalidURI3 = "clusters/" + CLUSTER_NAME + "/workflows/Workflow_0/jobs/xxx/tasks/xxx/userContent"; // task not exist Entity validEntity = Entity.entity("{\"k1\":\"v1\"}", MediaType.APPLICATION_JSON_TYPE); Entity invalidEntity = Entity.entity("{\"k1\":{}}", MediaType.APPLICATION_JSON_TYPE); // not Map<String, String> Map<String, String> validCmd = ImmutableMap.of("command", "update"); Map<String, String> invalidCmd = ImmutableMap.of("command", "delete"); // cmd not supported get(invalidURI1, null, Response.Status.NOT_FOUND.getStatusCode(), false); get(invalidURI2, null, Response.Status.NOT_FOUND.getStatusCode(), false); get(invalidURI3, null, Response.Status.NOT_FOUND.getStatusCode(), false); // The following two lines should get OK even though they should be NOT FOUND because the client // side code create UserContent znodes when not found post(invalidURI1, validCmd, validEntity, Response.Status.OK.getStatusCode()); post(invalidURI2, validCmd, validEntity, Response.Status.OK.getStatusCode()); post(validURI, invalidCmd, validEntity, Response.Status.BAD_REQUEST.getStatusCode()); post(validURI, validCmd, invalidEntity, Response.Status.BAD_REQUEST.getStatusCode()); System.out.println("End test :" + TestHelper.getTestMethodName()); } }
9,298
0
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest
Create_ds/helix/helix-rest/src/test/java/org/apache/helix/rest/server/TestHelixRestObjectNameFactory.java
package org.apache.helix.rest.server; /* * 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 javax.management.ObjectName; import org.testng.Assert; import org.testng.annotations.Test; public class TestHelixRestObjectNameFactory { @Test public void createsObjectNameWithDomainInInput() { HelixRestObjectNameFactory f = new HelixRestObjectNameFactory("namespace"); ObjectName objectName = f.createName("type", "org.apache.helix.rest", "something.with.dots"); Assert.assertEquals(objectName.getDomain(), "org.apache.helix.rest"); } @Test public void createsObjectNameWithNameAsKeyPropertyName() { HelixRestObjectNameFactory f = new HelixRestObjectNameFactory("helix.rest"); ObjectName objectName = f.createName("counter", "org.apache.helix.rest", "something.with.dots"); Assert.assertEquals(objectName.getKeyProperty("name"), "something.with.dots"); Assert.assertEquals(objectName.getKeyProperty("namespace"), "helix.rest"); Assert.assertEquals(objectName.getKeyProperty("type"), "counter"); } }
9,299