Java Code Examples for org.apache.helix.HelixAdmin#addStateModelDef()

The following examples show how to use org.apache.helix.HelixAdmin#addStateModelDef() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestZkHelixAdmin.java    From helix with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisableResource() {
  String className = TestHelper.getTestClassName();
  String methodName = TestHelper.getTestMethodName();
  String clusterName = className + "_" + methodName;
  System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
  HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
  admin.addCluster(clusterName, true);
  Assert.assertTrue(ZKUtil.isClusterSetup(clusterName, _gZkClient), "Cluster should be setup");
  String resourceName = "TestDB";
  admin.addStateModelDef(clusterName, "MasterSlave",
      new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave()));
  admin.addResource(clusterName, resourceName, 4, "MasterSlave");
  admin.enableResource(clusterName, resourceName, false);
  BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
  HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
  PropertyKey.Builder keyBuilder = accessor.keyBuilder();
  IdealState idealState = accessor.getProperty(keyBuilder.idealStates(resourceName));
  Assert.assertFalse(idealState.isEnabled());
  admin.enableResource(clusterName, resourceName, true);
  idealState = accessor.getProperty(keyBuilder.idealStates(resourceName));
  Assert.assertTrue(idealState.isEnabled());

  admin.dropCluster(clusterName);
  System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
 
Example 2
Source File: TestZkHelixAdmin.java    From helix with Apache License 2.0 6 votes vote down vote up
/**
 * Test enabledWagedRebalance by checking the rebalancer class name changed.
 */
@Test
public void testEnableWagedRebalance() {
  String className = TestHelper.getTestClassName();
  String methodName = TestHelper.getTestMethodName();
  String clusterName = className + "_" + methodName;
  String testResourcePrefix = "TestResource";
  HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
  admin.addCluster(clusterName, true);
  admin.addStateModelDef(clusterName, "MasterSlave", new MasterSlaveSMD());

  // Add an IdealState
  IdealState idealState = new IdealState(testResourcePrefix);
  idealState.setNumPartitions(3);
  idealState.setStateModelDefRef("MasterSlave");
  idealState.setRebalanceMode(IdealState.RebalanceMode.FULL_AUTO);
  admin.addResource(clusterName, testResourcePrefix, idealState);

  admin.enableWagedRebalance(clusterName, Collections.singletonList(testResourcePrefix));
  IdealState is = admin.getResourceIdealState(clusterName, testResourcePrefix);
  Assert.assertEquals(is.getRebalancerClassName(), WagedRebalancer.class.getName());
}
 
Example 3
Source File: HelixSetupUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private static void createBrokerResourceIfNeeded(String helixClusterName, HelixAdmin helixAdmin,
    boolean enableBatchMessageMode) {
  // Add state model definition if needed
  String stateModel =
      PinotHelixBrokerResourceOnlineOfflineStateModelGenerator.PINOT_BROKER_RESOURCE_ONLINE_OFFLINE_STATE_MODEL;
  StateModelDefinition stateModelDef = helixAdmin.getStateModelDef(helixClusterName, stateModel);
  if (stateModelDef == null) {
    LOGGER.info("Adding state model: {}", stateModel);
    helixAdmin.addStateModelDef(helixClusterName, stateModel,
        PinotHelixBrokerResourceOnlineOfflineStateModelGenerator.generatePinotStateModelDefinition());
  }

  // Add broker resource if needed
  if (helixAdmin.getResourceIdealState(helixClusterName, BROKER_RESOURCE_INSTANCE) == null) {
    LOGGER.info("Adding resource: {}", BROKER_RESOURCE_INSTANCE);
    IdealState idealState = new CustomModeISBuilder(BROKER_RESOURCE_INSTANCE).setStateModel(stateModel).build();
    idealState.setBatchMessageMode(enableBatchMessageMode);
    helixAdmin.addResource(helixClusterName, BROKER_RESOURCE_INSTANCE, idealState);
  }
}
 
Example 4
Source File: HelixBootstrapUpgradeUtil.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Add new state model def to ambry cluster in enabled datacenter(s).
 */
private void addStateModelDef() {
  for (Map.Entry<String, HelixAdmin> entry : adminForDc.entrySet()) {
    // Add a cluster entry in every enabled DC
    String dcName = entry.getKey();
    HelixAdmin admin = entry.getValue();
    boolean isClusterPresent = zkClientForDc.get(dcName) == null ? admin.getClusters().contains(clusterName)
        : ZKUtil.isClusterSetup(clusterName, zkClientForDc.get(dcName));
    if (!isClusterPresent) {
      throw new IllegalStateException("Cluster " + clusterName + " in " + dcName + " doesn't exist!");
    }
    if (!admin.getStateModelDefs(clusterName).contains(stateModelDef)) {
      info("Adding state model def {} in {} for cluster {}", stateModelDef, dcName, clusterName);
      admin.addStateModelDef(clusterName, stateModelDef, getStateModelDefinition(stateModelDef));
    } else {
      info("{} in {} already has state model def {}, skip adding operation", clusterName, dcName, stateModelDef);
    }
  }
}
 
Example 5
Source File: HelixSetupUtils.java    From uReplicator with Apache License 2.0 5 votes vote down vote up
public static void createHelixClusterIfNeeded(String helixClusterName, String zkPath) {
  final HelixAdmin admin = new ZKHelixAdmin(zkPath);

  if (admin.getClusters().contains(helixClusterName)) {
    LOGGER.info("cluster already exist, skipping it.. ********************************************* ");
    return;
  }

  LOGGER.info("Creating a new cluster, as the helix cluster : " + helixClusterName
      + " was not found ********************************************* ");
  admin.addCluster(helixClusterName, false);

  LOGGER.info("Enable mirror maker machines auto join.");
  final HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER)
      .forCluster(helixClusterName).build();

  final Map<String, String> props = new HashMap<String, String>();
  props.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, String.valueOf(true));
  props.put(MessageType.STATE_TRANSITION + "." + HelixTaskExecutor.MAX_THREADS,
      String.valueOf(100));

  admin.setConfig(scope, props);

  LOGGER.info("Adding state model definition named : OnlineOffline generated using : "
      + OnlineOfflineStateModel.class.toString()
      + " ********************************************** ");

  // add state model definition
  admin.addStateModelDef(helixClusterName, "OnlineOffline", OnlineOfflineStateModel.build());
  LOGGER.info("New Cluster setup completed... ********************************************** ");
}
 
Example 6
Source File: TestMessageThrottle2.java    From helix with Apache License 2.0 5 votes vote down vote up
private void startAdmin() {
  HelixAdmin admin = new ZKHelixAdmin(ZK_ADDR);

  // create cluster
  System.out.println("Creating cluster: " + _clusterName);
  admin.addCluster(_clusterName, true);

  // add MasterSlave state mode definition
  admin.addStateModelDef(_clusterName, "MasterSlave",
      new StateModelDefinition(generateConfigForMasterSlave()));

  // ideal-state znrecord
  ZNRecord record = new ZNRecord(_resourceName);
  record.setSimpleField("IDEAL_STATE_MODE", "AUTO");
  record.setSimpleField("NUM_PARTITIONS", "1");
  record.setSimpleField("REPLICAS", "2");
  record.setSimpleField("STATE_MODEL_DEF_REF", "MasterSlave");
  record.setListField(_resourceName, Arrays.asList("node1", "node2"));

  admin.setResourceIdealState(_clusterName, _resourceName, new IdealState(record));

  ConstraintItemBuilder builder = new ConstraintItemBuilder();

  // limit one transition message at a time across the entire cluster
  builder.addConstraintAttribute("MESSAGE_TYPE", "STATE_TRANSITION")
      // .addConstraintAttribute("INSTANCE", ".*") // un-comment this line if using instance-level
      // constraint
      .addConstraintAttribute("CONSTRAINT_VALUE", "1");
  admin.setConstraint(_clusterName, ClusterConstraints.ConstraintType.MESSAGE_CONSTRAINT,
      "constraint1", builder.build());
}
 
Example 7
Source File: TestZkHelixAdmin.java    From helix with Apache License 2.0 5 votes vote down vote up
@Test
public void testDropResource() {
  String className = TestHelper.getTestClassName();
  String methodName = TestHelper.getTestMethodName();
  String clusterName = className + "_" + methodName;

  System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));

  HelixAdmin tool = new ZKHelixAdmin(_gZkClient);
  tool.addCluster(clusterName, true);
  Assert.assertTrue(ZKUtil.isClusterSetup(clusterName, _gZkClient), "Cluster should be setup");

  tool.addStateModelDef(clusterName, "MasterSlave",
      new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave()));
  tool.addResource(clusterName, "test-db", 4, "MasterSlave");
  Map<String, String> resourceConfig = new HashMap<>();
  resourceConfig.put("key1", "value1");
  tool.setConfig(new HelixConfigScopeBuilder(ConfigScopeProperty.RESOURCE).forCluster(clusterName)
      .forResource("test-db").build(), resourceConfig);

  PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
  Assert.assertTrue(_gZkClient.exists(keyBuilder.idealStates("test-db").getPath()),
      "test-db ideal-state should exist");
  Assert.assertTrue(_gZkClient.exists(keyBuilder.resourceConfig("test-db").getPath()),
      "test-db resource config should exist");

  tool.dropResource(clusterName, "test-db");
  Assert.assertFalse(_gZkClient.exists(keyBuilder.idealStates("test-db").getPath()),
      "test-db ideal-state should be dropped");
  Assert.assertFalse(_gZkClient.exists(keyBuilder.resourceConfig("test-db").getPath()),
      "test-db resource config should be dropped");

  tool.dropCluster(clusterName);
  System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
 
Example 8
Source File: HelixBootstrapUpgradeUtil.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize a map of dataCenter to HelixAdmin based on the given zk Connect Strings.
 */
private void maybeAddCluster() {
  for (Map.Entry<String, HelixAdmin> entry : adminForDc.entrySet()) {
    // Add a cluster entry in every DC
    String dcName = entry.getKey();
    HelixAdmin admin = entry.getValue();
    boolean isClusterPresent = zkClientForDc.get(dcName) == null ? admin.getClusters().contains(clusterName)
        : ZKUtil.isClusterSetup(clusterName, zkClientForDc.get(dcName));
    if (!isClusterPresent) {
      info("Adding cluster {} in {}", clusterName, dcName);
      admin.addCluster(clusterName);
      admin.addStateModelDef(clusterName, stateModelDef, getStateModelDefinition(stateModelDef));
    }
  }
}
 
Example 9
Source File: TestZkHelixAdmin.java    From helix with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetResourcesWithTag() {
  String TEST_TAG = "TestTAG";

  String className = TestHelper.getTestClassName();
  String methodName = TestHelper.getTestMethodName();
  String clusterName = className + "_" + methodName;

  HelixAdmin tool = new ZKHelixAdmin(_gZkClient);
  tool.addCluster(clusterName, true);
  Assert.assertTrue(ZKUtil.isClusterSetup(clusterName, _gZkClient));

  tool.addStateModelDef(clusterName, "OnlineOffline",
      new StateModelDefinition(StateModelConfigGenerator.generateConfigForOnlineOffline()));

  for (int i = 0; i < 4; i++) {
    String instanceName = "host" + i + "_9999";
    InstanceConfig config = new InstanceConfig(instanceName);
    config.setHostName("host" + i);
    config.setPort("9999");
    // set tag to two instances
    if (i < 2) {
      config.addTag(TEST_TAG);
    }
    tool.addInstance(clusterName, config);
    tool.enableInstance(clusterName, instanceName, true);
    String path = PropertyPathBuilder.instance(clusterName, instanceName);
    AssertJUnit.assertTrue(_gZkClient.exists(path));
  }

  for (int i = 0; i < 4; i++) {
    String resourceName = "database_" + i;
    IdealState is = new IdealState(resourceName);
    is.setStateModelDefRef("OnlineOffline");
    is.setNumPartitions(2);
    is.setRebalanceMode(IdealState.RebalanceMode.FULL_AUTO);
    is.setReplicas("1");
    is.enable(true);
    if (i < 2) {
      is.setInstanceGroupTag(TEST_TAG);
    }
    tool.addResource(clusterName, resourceName, is);
  }

  List<String> allResources = tool.getResourcesInCluster(clusterName);
  List<String> resourcesWithTag = tool.getResourcesInClusterWithTag(clusterName, TEST_TAG);
  AssertJUnit.assertEquals(allResources.size(), 4);
  AssertJUnit.assertEquals(resourcesWithTag.size(), 2);

  tool.dropCluster(clusterName);
}
 
Example 10
Source File: TestZkHelixAdmin.java    From helix with Apache License 2.0 4 votes vote down vote up
/**
 * Test addResourceWithWeight() and validateResourcesForWagedRebalance() by trying to add a resource with incomplete ResourceConfig.
 */
@Test
public void testAddResourceWithWeightAndValidation()
    throws IOException {
  String className = TestHelper.getTestClassName();
  String methodName = TestHelper.getTestMethodName();
  String clusterName = className + "_" + methodName;
  String mockInstance = "MockInstance";
  String testResourcePrefix = "TestResource";
  HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
  admin.addCluster(clusterName, true);
  admin.addStateModelDef(clusterName, "MasterSlave", new MasterSlaveSMD());

  // Create a dummy instance
  InstanceConfig instanceConfig = new InstanceConfig(mockInstance);
  Map<String, Integer> mockInstanceCapacity =
      ImmutableMap.of("WCU", 100, "RCU", 100, "STORAGE", 100);
  instanceConfig.setInstanceCapacityMap(mockInstanceCapacity);
  admin.addInstance(clusterName, instanceConfig);
  MockParticipantManager mockParticipantManager =
      new MockParticipantManager(ZK_ADDR, clusterName, mockInstance);
  mockParticipantManager.syncStart();

  IdealState idealState = new IdealState(testResourcePrefix);
  idealState.setNumPartitions(3);
  idealState.setStateModelDefRef("MasterSlave");
  idealState.setRebalanceMode(IdealState.RebalanceMode.FULL_AUTO);

  ResourceConfig resourceConfig = new ResourceConfig(testResourcePrefix);
  // validate
  Map<String, Boolean> validationResult = admin.validateResourcesForWagedRebalance(clusterName,
      Collections.singletonList(testResourcePrefix));
  Assert.assertEquals(validationResult.size(), 1);
  Assert.assertFalse(validationResult.get(testResourcePrefix));
  try {
    admin.addResourceWithWeight(clusterName, idealState, resourceConfig);
    Assert.fail();
  } catch (HelixException e) {
    // OK since resourceConfig is empty
  }

  // Set PARTITION_CAPACITY_MAP
  Map<String, String> capacityDataMap =
      ImmutableMap.of("WCU", "1", "RCU", "2", "STORAGE", "3");
  resourceConfig.getRecord()
      .setMapField(ResourceConfig.ResourceConfigProperty.PARTITION_CAPACITY_MAP.name(),
          Collections.singletonMap(ResourceConfig.DEFAULT_PARTITION_KEY,
              OBJECT_MAPPER.writeValueAsString(capacityDataMap)));

  // validate
  validationResult = admin.validateResourcesForWagedRebalance(clusterName,
      Collections.singletonList(testResourcePrefix));
  Assert.assertEquals(validationResult.size(), 1);
  Assert.assertFalse(validationResult.get(testResourcePrefix));

  // Add the capacity key to ClusterConfig
  HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
  PropertyKey.Builder keyBuilder = dataAccessor.keyBuilder();
  ClusterConfig clusterConfig = dataAccessor.getProperty(keyBuilder.clusterConfig());
  clusterConfig.setInstanceCapacityKeys(Arrays.asList("WCU", "RCU", "STORAGE"));
  dataAccessor.setProperty(keyBuilder.clusterConfig(), clusterConfig);

  // Should succeed now
  Assert.assertTrue(admin.addResourceWithWeight(clusterName, idealState, resourceConfig));
  // validate
  validationResult = admin.validateResourcesForWagedRebalance(clusterName,
      Collections.singletonList(testResourcePrefix));
  Assert.assertEquals(validationResult.size(), 1);
  Assert.assertTrue(validationResult.get(testResourcePrefix));
}
 
Example 11
Source File: TestAddBuiltInStateModelDef.java    From helix with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
  String className = TestHelper.getTestClassName();
  String methodName = TestHelper.getTestMethodName();
  String clusterName = className + "_" + methodName;

  System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
  HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
  admin.addCluster(clusterName);
  admin.addStateModelDef(clusterName, BuiltInStateModelDefinitions.MasterSlave.getStateModelDefinition().getId(),
                         BuiltInStateModelDefinitions.MasterSlave.getStateModelDefinition());
  ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName);
  controller.syncStart();

  // controller shall create all built-in state model definitions
  final BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
  final PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
  boolean ret = TestHelper.verify(new TestHelper.Verifier() {

    @Override
    public boolean verify() throws Exception {
      for (BuiltInStateModelDefinitions def : BuiltInStateModelDefinitions.values()) {
        String path = keyBuilder.stateModelDef(def.getStateModelDefinition().getId()).getPath();
        boolean exist = baseAccessor.exists(path, 0);
        if (!exist) {
          return false;
        }

        // make sure MasterSlave is not over-written
        if (def == BuiltInStateModelDefinitions.MasterSlave) {
          Stat stat = new Stat();
          baseAccessor.get(path, stat, 0);
          if (stat.getVersion() != 0) {
            return false;
          }
        }
      }
      return true;
    }
  }, 10 * 1000);
  Assert.assertTrue(ret);
  controller.syncStop();
  admin.dropCluster(clusterName);
  System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
 
Example 12
Source File: LockManagerDemo.java    From helix with Apache License 2.0 4 votes vote down vote up
/**
 * LockManagerDemo clusterName, numInstances, lockGroupName, numLocks
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
  final String zkAddress = "localhost:2199";
  final String clusterName = "lock-manager-demo";
  final String lockGroupName = "lock-group";
  final int numInstances = 3;
  final int numPartitions = 12;
  final boolean startController = false;
  HelixManager controllerManager = null;
  Thread[] processArray;
  processArray = new Thread[numInstances];
  try {
    startLocalZookeeper(2199);
    HelixAdmin admin = new ZKHelixAdmin(zkAddress);
    admin.addCluster(clusterName, true);
    StateModelConfigGenerator generator = new StateModelConfigGenerator();
    admin.addStateModelDef(clusterName, "OnlineOffline",
        new StateModelDefinition(generator.generateConfigForOnlineOffline()));
    admin.addResource(clusterName, lockGroupName, numPartitions, "OnlineOffline",
        RebalanceMode.FULL_AUTO.toString());
    admin.rebalance(clusterName, lockGroupName, 1);
    for (int i = 0; i < numInstances; i++) {
      final String instanceName = "localhost_" + (12000 + i);
      processArray[i] = new Thread(new Runnable() {

        @Override
        public void run() {
          LockProcess lockProcess = null;

          try {
            lockProcess = new LockProcess(clusterName, zkAddress, instanceName, startController);
            lockProcess.start();
            Thread.currentThread().join();
          } catch (InterruptedException e) {
            System.out.println(instanceName + "Interrupted");
            if (lockProcess != null) {
              lockProcess.stop();
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

      });
      processArray[i].start();
    }
    Thread.sleep(3000);
    controllerManager =
        HelixControllerMain.startHelixController(zkAddress, clusterName, "controller",
            HelixControllerMain.STANDALONE);
    Thread.sleep(5000);
    printStatus(admin, clusterName, lockGroupName);
    System.out.println("Stopping localhost_12000");
    processArray[0].interrupt();
    Thread.sleep(3000);
    printStatus(admin, clusterName, lockGroupName);
    Thread.currentThread().join();
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if (controllerManager != null) {
      controllerManager.disconnect();
    }
    for (Thread process : processArray) {
      if (process != null) {
        process.interrupt();
      }
    }
  }
}