{
List<String> InstanceNames = _admin.getInstancesInCluster(clusterName);
// ensure we get the same idealState with the same set of instances
Collections.sort(InstanceNames);
IdealState idealState = _admin.getResourceIdealState(clusterName, resourceName);
if (idealState == null)
{
throw new HelixException("Resource: " + resourceName + " has NOT been added yet");
}
idealState.setReplicas(Integer.toString(replica));
int partitions = idealState.getNumPartitions();
String stateModelName = idealState.getStateModelDefRef();
StateModelDefinition stateModDef =
_admin.getStateModelDef(clusterName, stateModelName);
if (stateModDef == null)
{
throw new HelixException("cannot find state model: " + stateModelName);
}
// StateModelDefinition def = new StateModelDefinition(stateModDef);
List<String> statePriorityList = stateModDef.getStatesPriorityList();
String masterStateValue = null;
String slaveStateValue = null;
replica--;
for (String state : statePriorityList)
{
String count = stateModDef.getNumInstancesPerState(state);
if (count.equals("1"))
{
if (masterStateValue != null)
{
throw new HelixException("Invalid or unsupported state model definition");
}
masterStateValue = state;
}
else if (count.equalsIgnoreCase("R"))
{
if (slaveStateValue != null)
{
throw new HelixException("Invalid or unsupported state model definition");
}
slaveStateValue = state;
}
else if (count.equalsIgnoreCase("N"))
{
if (!(masterStateValue == null && slaveStateValue == null))
{
throw new HelixException("Invalid or unsupported state model definition");
}
replica = InstanceNames.size() - 1;
masterStateValue = slaveStateValue = state;
}
}
if (masterStateValue == null && slaveStateValue == null)
{
throw new HelixException("Invalid or unsupported state model definition");
}
if (masterStateValue == null)
{
masterStateValue = slaveStateValue;
}
if (idealState.getIdealStateMode() != IdealStateModeProperty.AUTO_REBALANCE)
{
ZNRecord newIdealState =
IdealStateCalculatorForStorageNode.calculateIdealState(InstanceNames,
partitions,
replica,
keyPrefix,
masterStateValue,
slaveStateValue);
// for now keep mapField in AUTO mode and remove listField in CUSTOMIZED mode
if (idealState.getIdealStateMode() == IdealStateModeProperty.AUTO)
{
idealState.getRecord().setListFields(newIdealState.getListFields());
idealState.getRecord().setMapFields(newIdealState.getMapFields());
}
if (idealState.getIdealStateMode() == IdealStateModeProperty.CUSTOMIZED)
{
idealState.getRecord().setMapFields(newIdealState.getMapFields());
}
}
else
{
for (int i = 0; i < partitions; i++)
{
String partitionName = keyPrefix + "_" + i;
idealState.getRecord().setMapField(partitionName, new HashMap<String, String>());
idealState.getRecord().setListField(partitionName, new ArrayList<String>());
}
}
_admin.setResourceIdealState(clusterName, resourceName, idealState);
}