index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskRebalancerParallel.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.tools.ClusterVerifiers.ClusterLiveNodesVerifier; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestTaskRebalancerParallel extends TaskTestBase { final int PARALLEL_COUNT = 2; final int TASK_COUNT = 30; @BeforeClass public void beforeClass() throws Exception { _numDbs = 4; _partitionVary = false; super.beforeClass(); } /** * This test starts 4 jobs in job queue, the job all stuck, and verify that * (1) the number of running job does not exceed configured max allowed parallel jobs * (2) one instance can only be assigned to one job in the workflow */ @Test public void testWhenDisallowOverlapJobAssignment() throws Exception { String queueName = TestHelper.getTestMethodName(); WorkflowConfig.Builder cfgBuilder = new WorkflowConfig.Builder(queueName); cfgBuilder.setParallelJobs(PARALLEL_COUNT); cfgBuilder.setAllowOverlapJobAssignment(false); JobQueue.Builder queueBuild = new JobQueue.Builder(queueName).setWorkflowConfig(cfgBuilder.build()); JobQueue queue = queueBuild.build(); _driver.createQueue(queue); List<JobConfig.Builder> jobConfigBuilders = new ArrayList<JobConfig.Builder>(); for (String testDbName : _testDbs) { jobConfigBuilders.add( new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(testDbName) .setTargetPartitionStates(Collections.singleton("SLAVE")) .setJobCommandConfigMap(Collections.singletonMap(MockTask.JOB_DELAY, "1000"))); } _driver.stop(queueName); for (int i = 0; i < jobConfigBuilders.size(); ++i) { _driver.enqueueJob(queueName, "job_" + (i + 1), jobConfigBuilders.get(i)); } _driver.resume(queueName); Thread.sleep(1000L); Assert.assertTrue(TaskTestUtil.pollForWorkflowParallelState(_driver, queueName)); } /** * This test starts 4 jobs in job queue, the job all stuck, and verify that * (1) the number of running job does not exceed configured max allowed parallel jobs * (2) one instance can be assigned to multiple jobs in the workflow when allow overlap assignment */ @Test (dependsOnMethods = {"testWhenDisallowOverlapJobAssignment"}) public void testWhenAllowOverlapJobAssignment() throws Exception { // Disable all participants except one to enforce all assignment to be on one host for (int i = 1; i < _numNodes; i++) { _participants[i].syncStop(); } ClusterLiveNodesVerifier verifier = new ClusterLiveNodesVerifier(_gZkClient, CLUSTER_NAME, Collections.singletonList(_participants[0].getInstanceName())); Assert.assertTrue(verifier.verifyByPolling()); String queueName = TestHelper.getTestMethodName(); WorkflowConfig.Builder cfgBuilder = new WorkflowConfig.Builder(queueName); cfgBuilder.setParallelJobs(PARALLEL_COUNT); cfgBuilder.setAllowOverlapJobAssignment(true); JobQueue.Builder queueBuild = new JobQueue.Builder(queueName).setWorkflowConfig(cfgBuilder.build()); JobQueue queue = queueBuild.build(); _driver.createQueue(queue); // Create jobs that can be assigned to any instances List<JobConfig.Builder> jobConfigBuilders = new ArrayList<JobConfig.Builder>(); for (int i = 0; i < PARALLEL_COUNT; i++) { List<TaskConfig> taskConfigs = new ArrayList<TaskConfig>(); for (int j = 0; j < TASK_COUNT; j++) { taskConfigs.add(new TaskConfig.Builder().setTaskId("job_" + (i + 1) + "_task_" + j) .setCommand(MockTask.TASK_COMMAND).build()); } jobConfigBuilders.add(new JobConfig.Builder().addTaskConfigs(taskConfigs)); } _driver.stop(queueName); for (int i = 0; i < jobConfigBuilders.size(); ++i) { _driver.enqueueJob(queueName, "job_" + (i + 1), jobConfigBuilders.get(i)); } _driver.resume(queueName); Thread.sleep(2000); Assert.assertTrue(TaskTestUtil.pollForWorkflowParallelState(_driver, queueName)); } }
9,600
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestDropOnParticipantReset.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 org.apache.helix.TestHelper; import org.apache.helix.model.InstanceConfig; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestDropOnParticipantReset extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _numDbs = 0; _numPartitions = 0; _numReplicas = 0; _numNodes = 1; // Only bring up 1 instance super.beforeClass(); } /** * Tests that upon Participant reconnect, the Controller correctly sends the current * state of the task partition to DROPPED. This is to avoid a resource leak in case of a * Participant disconnect/reconnect and an ensuing reset() on all of the partitions on that * Participant. */ @Test public void testDropOnParticipantReset() throws InterruptedException { // Create a workflow with some long-running jobs in progress String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB"; Workflow.Builder builder = new Workflow.Builder(workflowName); List<TaskConfig> taskConfigs = new ArrayList<>(); for (int j = 0; j < 2; j++) { // 2 tasks to ensure that they execute String taskID = jobName + "_TASK_" + j; TaskConfig.Builder taskConfigBuilder = new TaskConfig.Builder(); taskConfigBuilder.setTaskId(taskID).setCommand(MockTask.TASK_COMMAND) .addConfig(MockTask.JOB_DELAY, "3000"); taskConfigs.add(taskConfigBuilder.build()); } JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setMaxAttemptsPerTask(10).setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG) .addTaskConfigs(taskConfigs).setIgnoreDependentJobFailure(true) // 1 task at a time .setNumConcurrentTasksPerInstance(1); builder.addJob(jobName, jobBuilder); // Modify maxConcurrentTask for the instance so that it only accepts 1 task at most InstanceConfig instanceConfig = _gSetupTool.getClusterManagementTool() .getInstanceConfig(CLUSTER_NAME, _participants[0].getInstanceName()); instanceConfig.setMaxConcurrentTask(1); _gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, _participants[0].getInstanceName(), instanceConfig); // Start the workflow _driver.start(builder.build()); _driver.pollForJobState(workflowName, workflowName + "_" + jobName, TaskState.IN_PROGRESS); Thread.sleep(1500L); // Wait for the Participant to process the message // Stop and start the participant to mimic a connection issue _participants[0].syncStop(); // Upon starting the participant, the first task partition should be dropped and assigned anew // on the instance. Then the rest of the tasks will execute and the workflow will complete startParticipant(0); TaskState workflowState = _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); TaskState jobState = _driver.pollForJobState(workflowName, workflowName + "_" + jobName, TaskState.COMPLETED); Assert.assertEquals(workflowState, TaskState.COMPLETED); Assert.assertEquals(jobState, TaskState.COMPLETED); } }
9,601
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestStoppingWorkflowAndJob.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.apache.helix.HelixException; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; /** * Test to check if workflow correctly behaves when it's target state is set to STOP and the tasks * have some delay in their cancellation. */ public class TestStoppingWorkflowAndJob extends TaskTestBase { private static final String DATABASE = WorkflowGenerator.DEFAULT_TGT_DB; private CountDownLatch latch = new CountDownLatch(1); @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; _numNodes = 3; super.beforeClass(); // Stop participants that have been started in super class for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } // Start new participants that have new TaskStateModel (NewMockTask) information _participants = new MockParticipantManager[_numNodes]; for (int i = 0; i < _numNodes; i++) { startParticipantAndRegisterNewMockTask(i); } } @Test public void testStoppingQueueFailToStop() throws Exception { // Test to check if waitToStop method correctly throws an Exception if Queue stuck in STOPPING // state. String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder0 = new JobConfig.Builder().setWorkflow(jobQueueName).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("JOB0", jobBuilder0); _driver.start(jobQueue.build()); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"), TaskState.IN_PROGRESS); boolean exceptionHappened = false; try { _driver.waitToStop(jobQueueName, 5000L); } catch (HelixException e) { exceptionHappened = true; } _driver.pollForWorkflowState(jobQueueName, TaskState.STOPPING); Assert.assertTrue(exceptionHappened); latch.countDown(); } @Test(dependsOnMethods = "testStoppingQueueFailToStop") public void testStopWorkflowInstanceOffline() throws Exception { // Test to check if workflow and jobs go to STOPPED state when the assigned participants of the // tasks are not live anymore. latch = new CountDownLatch(1); int numberOfTasks = 10; // Stop all participant except participant0 for (int i = 1; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } // Start a new workflow String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(workflowName).setNumberOfTasks(numberOfTasks) .setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder); // Start the workflow and make sure it goes to IN_PROGRESS state. _driver.start(workflowBuilder.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Make sure all of the tasks within the job are assigned and have RUNNING state String participant0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); for (int i = 0; i < numberOfTasks; i++) { final int taskNumber = i; Assert.assertTrue(TestHelper.verify(() -> (TaskPartitionState.RUNNING .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getPartitionState(taskNumber)) && participant0 .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getAssignedParticipant(taskNumber))), TestHelper.WAIT_DURATION)); } // STOP the workflow and make sure it goes to STOPPING state _driver.stop(workflowName); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.STOPPING); // Stop the remaining participant and the controller _controller.syncStop(); super.stopParticipant(0); // Start the controller and make sure the workflow and job go to STOPPED state _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); // Start other participants to allow controller process the workflows. Otherwise due to no // global capacity, the workflows will not be processed for (int i = 1; i < _numNodes; i++) { startParticipantAndRegisterNewMockTask(i); } _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.STOPPED); _driver.pollForWorkflowState(workflowName, TaskState.STOPPED); // Make sure all of the tasks within the job are assigned and have DROPPED state for (int i = 0; i < numberOfTasks; i++) { final int taskNumber = i; Assert.assertTrue(TestHelper.verify(() -> (TaskPartitionState.DROPPED .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getPartitionState(taskNumber)) && participant0 .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getAssignedParticipant(taskNumber))), TestHelper.WAIT_DURATION)); } latch.countDown(); } private void startParticipantAndRegisterNewMockTask(int participantIndex) { Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(NewMockTask.TASK_COMMAND, NewMockTask::new); String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + participantIndex); _participants[participantIndex] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[participantIndex].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[participantIndex], taskFactoryReg)); _participants[participantIndex].syncStart(); } /** * A mock task that extents MockTask class and stuck in running when cancel is called. */ private class NewMockTask extends MockTask { NewMockTask(TaskCallbackContext context) { super(context); } @Override public void cancel() { try { latch.await(); } catch (Exception e) { // Pass } super.cancel(); } } }
9,602
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestContextRedundantUpdates.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This test checks of the workflow and job context get updates only if the update is necessary */ public class TestContextRedundantUpdates extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _numDbs = 1; _numPartitions = 1; super.beforeClass(); } @Test public void testFinishWorkflowContextNoUpdate() throws Exception { // Create a workflow with short running job String workflowName1 = TestHelper.getTestMethodName() + "_1"; String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName1).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName1).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName1, TaskUtil.getNamespacedJobName(workflowName1, jobName), TaskState.COMPLETED); _driver.pollForWorkflowState(workflowName1, TaskState.COMPLETED); int initialWorkflowContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().workflowContextZNode(workflowName1)) .getRecord().getVersion(); // Create another workflow with short running job String workflowName2 = TestHelper.getTestMethodName() + "_2"; JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName2).setNumberOfTasks(10).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "5000")); Workflow.Builder workflowBuilder2 = new Workflow.Builder(workflowName2).addJob(jobName, jobBuilder2); // Start new workflow and make sure it gets completed. This would help us to make sure pipeline // has been run several times _driver.start(workflowBuilder2.build()); _driver.pollForWorkflowState(workflowName2, TaskState.COMPLETED); int finalWorkflowContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().workflowContextZNode(workflowName1)) .getRecord().getVersion(); Assert.assertEquals(initialWorkflowContextVersion, finalWorkflowContextVersion); } @Test public void testRunningWorkflowContextNoUpdate() throws Exception { // Create a workflow with a long running job String workflowName1 = TestHelper.getTestMethodName() + "_1"; String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName1).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName1).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName1, TaskUtil.getNamespacedJobName(workflowName1, jobName), TaskState.IN_PROGRESS); _driver.pollForWorkflowState(workflowName1, TaskState.IN_PROGRESS); int initialWorkflowContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().workflowContextZNode(workflowName1)) .getRecord().getVersion(); // Create another workflow with short running job String workflowName2 = TestHelper.getTestMethodName() + "_2"; JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName2).setNumberOfTasks(10).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "2000")); Workflow.Builder workflowBuilder2 = new Workflow.Builder(workflowName2).addJob(jobName, jobBuilder2); // Start new workflow and make sure it gets completed. This would help us to make sure pipeline // has been run several times _driver.start(workflowBuilder2.build()); _driver.pollForWorkflowState(workflowName2, TaskState.COMPLETED); int finalWorkflowContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().workflowContextZNode(workflowName1)) .getRecord().getVersion(); Assert.assertEquals(initialWorkflowContextVersion, finalWorkflowContextVersion); } @Test public void testRunningJobContextNoUpdate() throws Exception { // Create a workflow with a long running job String workflowName1 = TestHelper.getTestMethodName() + "_1"; String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName1).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName1).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName1, TaskUtil.getNamespacedJobName(workflowName1, jobName), TaskState.IN_PROGRESS); _driver.pollForWorkflowState(workflowName1, TaskState.IN_PROGRESS); // Make sure task has been assigned to the participant is in RUNNING state boolean isTaskAssignedAndRunning = TestHelper.verify(() -> { JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName1, jobName)); String participant = ctx.getAssignedParticipant(0); TaskPartitionState taskState = ctx.getPartitionState(0); return (participant != null && taskState.equals(TaskPartitionState.RUNNING)); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isTaskAssignedAndRunning); int initialJobContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().jobContextZNode(workflowName1, jobName)) .getRecord().getVersion(); // Create another workflow with short running job String workflowName2 = TestHelper.getTestMethodName() + "_2"; JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName2).setNumberOfTasks(10).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "2000")); Workflow.Builder workflowBuilder2 = new Workflow.Builder(workflowName2).addJob(jobName, jobBuilder2); // Start new workflow and make sure it gets completed. This would help us to make sure pipeline // has been run several times _driver.start(workflowBuilder2.build()); _driver.pollForWorkflowState(workflowName2, TaskState.COMPLETED); int finalJobContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().jobContextZNode(workflowName1, jobName)) .getRecord().getVersion(); Assert.assertEquals(initialJobContextVersion, finalJobContextVersion); } @Test public void testCompletedJobContextNoUpdate() throws Exception { // Create a workflow with a short running job String workflowName1 = TestHelper.getTestMethodName() + "_1"; String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName1).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName1).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName1, TaskUtil.getNamespacedJobName(workflowName1, jobName), TaskState.COMPLETED); _driver.pollForWorkflowState(workflowName1, TaskState.COMPLETED); int initialJobContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().jobContextZNode(workflowName1, jobName)) .getRecord().getVersion(); // Create another workflow with short running job String workflowName2 = TestHelper.getTestMethodName() + "_2"; JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setWorkflow(workflowName2).setNumberOfTasks(10).setNumConcurrentTasksPerInstance(100) .setTimeoutPerTask(Long.MAX_VALUE).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "2000")); Workflow.Builder workflowBuilder2 = new Workflow.Builder(workflowName2).addJob(jobName, jobBuilder2); // Start new workflow and make sure it gets completed. This would help us to make sure pipeline // has been run several times _driver.start(workflowBuilder2.build()); _driver.pollForWorkflowState(workflowName2, TaskState.COMPLETED); int finalJobContextVersion = _manager.getHelixDataAccessor() .getProperty( _manager.getHelixDataAccessor().keyBuilder().jobContextZNode(workflowName1, jobName)) .getRecord().getVersion(); Assert.assertEquals(initialJobContextVersion, finalJobContextVersion); } }
9,603
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestCurrentStateDropWithoutConfigs.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.HelixDataAccessor; import org.apache.helix.TestHelper; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.model.CurrentState; import org.apache.helix.model.LiveInstance; import org.apache.helix.task.TaskConstants; import org.apache.helix.task.TaskPartitionState; import org.testng.Assert; import org.testng.annotations.Test; /** * Test to make sure that current states of jobs are dropped if no JobConfig exists */ public class TestCurrentStateDropWithoutConfigs extends TaskTestBase { protected HelixDataAccessor _accessor; @Test public void testCurrentStateDropWithoutConfigs() throws Exception { String jobName = TestHelper.getTestMethodName() + "_0"; String taskName = jobName + "_0"; _accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor); LiveInstance liveInstance = _accessor .getProperty(_accessor.keyBuilder().liveInstance(_participants[0].getInstanceName())); CurrentState currentState = new CurrentState(jobName); currentState.setSessionId(liveInstance.getEphemeralOwner()); currentState.setStateModelDefRef(TaskConstants.STATE_MODEL_NAME); currentState.setState(taskName, TaskPartitionState.RUNNING.name()); currentState.setPreviousState(taskName, TaskPartitionState.INIT.name()); currentState.setStartTime(taskName, System.currentTimeMillis()); currentState.setEndTime(taskName, System.currentTimeMillis()); _accessor.setProperty(_accessor.keyBuilder() .taskCurrentState(_participants[0].getInstanceName(), liveInstance.getEphemeralOwner(), jobName), currentState); Assert.assertTrue(TestHelper.verify(() -> _accessor.getProperty(_accessor.keyBuilder() .taskCurrentState(_participants[0].getInstanceName(), liveInstance.getEphemeralOwner(), jobName)) == null, TestHelper.WAIT_DURATION * 10)); } }
9,604
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskRetryDelay.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestTaskRetryDelay extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; super.beforeClass(); } @Test public void testTaskRetryWithDelay() throws Exception { String jobResource = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG) .setMaxAttemptsPerTask(2).setCommand(MockTask.TASK_COMMAND).setWorkflow(jobResource) .setFailureThreshold(Integer.MAX_VALUE).setTaskRetryDelay(2000L) .setJobCommandConfigMap(ImmutableMap.of(MockTask.FAILURE_COUNT_BEFORE_SUCCESS, "2")); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait until the job completes. _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); long startTime = _driver.getWorkflowContext(jobResource).getStartTime(); long finishedTime = _driver.getWorkflowContext(jobResource).getFinishTime(); // It should finish and take more than 2 secs with the retry delay built in Assert.assertTrue(finishedTime - startTime >= 2000L); } @Test public void testTaskRetryWithoutDelay() throws Exception { String jobResource = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG) .setMaxAttemptsPerTask(2).setCommand(MockTask.TASK_COMMAND) .setFailureThreshold(Integer.MAX_VALUE) .setJobCommandConfigMap(ImmutableMap.of(MockTask.FAILURE_COUNT_BEFORE_SUCCESS, "1")); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait until the job completes. _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); long startTime = _driver.getWorkflowContext(jobResource).getStartTime(); long finishedTime = _driver.getWorkflowContext(jobResource).getFinishTime(); // It should have finished within less than 2 sec Assert.assertTrue(finishedTime - startTime <= 2000L); } }
9,605
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskConditionalRetry.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.Test; /** * Test Conditional Task Retry */ public class TestTaskConditionalRetry extends TaskTestBase { @Test public void test() throws Exception { int taskRetryCount = 5; int num_tasks = 5; String jobResource = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder(); jobBuilder.setCommand(MockTask.TASK_COMMAND).setTimeoutPerTask(10000) .setMaxAttemptsPerTask(taskRetryCount).setFailureThreshold(Integer.MAX_VALUE); // create each task configs. final int abortedTask = 1; final int failedTask = 2; final int exceptionTask = 3; List<TaskConfig> taskConfigs = new ArrayList<>(); for (int j = 0; j < num_tasks; j++) { TaskConfig.Builder configBuilder = new TaskConfig.Builder().setTaskId("task_" + j); switch (j) { case abortedTask: configBuilder.addConfig(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FATAL_FAILED.name()); break; case failedTask: configBuilder.addConfig(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FAILED.name()); break; case exceptionTask: configBuilder.addConfig(MockTask.THROW_EXCEPTION, Boolean.TRUE.toString()); break; default: break; } configBuilder.setTargetPartition(String.valueOf(j)); taskConfigs.add(configBuilder.build()); } jobBuilder.addTaskConfigs(taskConfigs); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait until the job completes. _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(jobResource)); for (int i = 0; i < num_tasks; i++) { TaskPartitionState state = ctx.getPartitionState(i); int retriedCount = ctx.getPartitionNumAttempts(i); String taskId = ctx.getTaskIdForPartition(i); if (taskId.equals("task_" + abortedTask)) { Assert.assertEquals(state, TaskPartitionState.TASK_ABORTED); Assert.assertEquals(retriedCount, 1); } else if (taskId.equals("task_" + failedTask) || taskId.equals("task_" + exceptionTask)) { Assert.assertEquals(state, TaskPartitionState.TASK_ERROR); Assert.assertEquals(taskRetryCount, retriedCount); } else { Assert.assertEquals(state, TaskPartitionState.COMPLETED); Assert.assertEquals(retriedCount, 1); } } } }
9,606
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestRuntimeJobDag.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.helix.task.JobDag; import org.apache.helix.task.RuntimeJobDag; import org.testng.Assert; import org.testng.annotations.Test; public class TestRuntimeJobDag { @Test public void testBuildJobQueueWithParallelismExceedingJobCount() { JobDag jobDag = new JobDag(); jobDag.addNode("parent"); jobDag.addParentToChild("parent", "child"); jobDag.addParentToChild("child", "grandchild"); RuntimeJobDag runtimeJobDag = new RuntimeJobDag(jobDag, true, Integer.MAX_VALUE, 1); Assert.assertEquals(runtimeJobDag.getNextJob(), "parent"); Assert.assertEquals(runtimeJobDag.getNextJob(), "child"); Assert.assertEquals(runtimeJobDag.getNextJob(), "grandchild"); } private Set<String> actualJobs; private Set<String> expectedJobs; @Test public void testQueue() { // Test a queue: 1->2->3->4, expect [4, 3, 2, 1] List<String> jobs_1 = new ArrayList<>(); jobs_1.add("4"); jobs_1.add("3"); jobs_1.add("2"); jobs_1.add("1"); RuntimeJobDag jobDag_1 = createJobDag(jobs_1); jobDag_1.addParentToChild("4", "3"); jobDag_1.addParentToChild("3", "2"); jobDag_1.addParentToChild("2", "1"); jobDag_1.validate(); jobDag_1.generateJobList(); Assert.assertTrue(jobDag_1.hasNextJob()); Assert.assertEquals(jobDag_1.getNextJob(), "4"); jobDag_1.finishJob("4"); Assert.assertEquals(jobDag_1.getNextJob(), "3"); jobDag_1.finishJob("3"); Assert.assertEquals(jobDag_1.getNextJob(), "2"); jobDag_1.finishJob("2"); Assert.assertEquals(jobDag_1.getNextJob(), "1"); jobDag_1.finishJob("1"); Assert.assertFalse(jobDag_1.hasNextJob()); } @Test(dependsOnMethods = "testQueue") public void testAddAndRemove() { // Test a queue: 1->2->3->4, expect [4, 3, 2, 1] List<String> jobs_1 = new ArrayList<>(); jobs_1.add("4"); jobs_1.add("3"); jobs_1.add("2"); jobs_1.add("1"); RuntimeJobDag jobDag_1 = createJobDag(jobs_1); jobDag_1.addParentToChild("4", "3"); jobDag_1.addParentToChild("3", "2"); jobDag_1.addParentToChild("2", "1"); jobDag_1.validate(); jobDag_1.generateJobList(); Assert.assertEquals(jobDag_1.getNextJob(), "4"); jobDag_1.finishJob("4"); jobDag_1.addNode("0"); jobDag_1.addParentToChild("0", "4"); Assert.assertEquals(jobDag_1.getNextJob(), "0"); // Should automatically re-generate job list jobDag_1.removeNode("3", true); jobDag_1.removeNode("0", true); Assert.assertEquals(jobDag_1.getNextJob(), "4"); // Should automatically re-generate job list and start over jobDag_1.finishJob("4"); Assert.assertEquals(jobDag_1.getNextJob(), "2"); // Should skip 3 } @Test(dependsOnMethods = "testAddAndRemove") public void testRegularDAGAndGenerateJobList() { List<String> jobs = new ArrayList<>(); // DAG from // https://en.wikipedia.org/wiki/Topological_sorting#/media/File:Directed_acyclic_graph_2.svg jobs.add("5"); jobs.add("11"); jobs.add("2"); jobs.add("7"); jobs.add("8"); jobs.add("9"); jobs.add("3"); jobs.add("10"); RuntimeJobDag jobDag = createJobDag(jobs); jobDag.addParentToChild("5", "11"); jobDag.addParentToChild("11", "2"); jobDag.addParentToChild("7", "11"); jobDag.addParentToChild("7", "8"); jobDag.addParentToChild("11", "9"); jobDag.addParentToChild("11", "10"); jobDag.addParentToChild("8", "9"); jobDag.addParentToChild("3", "8"); jobDag.addParentToChild("3", "10"); jobDag.generateJobList(); testRegularDAGHelper(jobDag); jobDag.generateJobList(); // Should have the original job list testRegularDAGHelper(jobDag); } private void testRegularDAGHelper(RuntimeJobDag jobDag) { emptyJobSets(); // 5, 7, 3 are un-parented nodes to start with actualJobs.add(jobDag.getNextJob()); actualJobs.add(jobDag.getNextJob()); actualJobs.add(jobDag.getNextJob()); Assert.assertFalse(jobDag.hasNextJob()); expectedJobs.add("5"); expectedJobs.add("7"); expectedJobs.add("3"); Assert.assertEquals(actualJobs, expectedJobs); jobDag.finishJob("3"); // Once 3 finishes, ready-list should still be empty Assert.assertFalse(jobDag.hasNextJob()); jobDag.finishJob("7"); // Once 3 and 7 both finish, 8 should be ready emptyJobSets(); actualJobs.add(jobDag.getNextJob()); expectedJobs.add("8"); Assert.assertEquals(actualJobs, expectedJobs); Assert.assertFalse(jobDag.hasNextJob()); jobDag.finishJob("5"); // Once 5 finishes, 11 should be ready emptyJobSets(); expectedJobs.add(jobDag.getNextJob()); actualJobs.add("11"); Assert.assertEquals(actualJobs, expectedJobs); Assert.assertFalse(jobDag.hasNextJob()); jobDag.finishJob("11"); jobDag.finishJob("8"); // Once 11 and 8 finish, 2, 9, 10 should be ready emptyJobSets(); actualJobs.add(jobDag.getNextJob()); actualJobs.add(jobDag.getNextJob()); actualJobs.add(jobDag.getNextJob()); expectedJobs.add("2"); expectedJobs.add("10"); expectedJobs.add("9"); Assert.assertEquals(actualJobs, expectedJobs); Assert.assertFalse(jobDag.hasNextJob()); // When all jobs are finished, no jobs should be left jobDag.finishJob("9"); jobDag.finishJob("10"); jobDag.finishJob("2"); Assert.assertFalse(jobDag.hasNextJob()); } private RuntimeJobDag createJobDag(List<String> jobs) { RuntimeJobDag jobDag = new RuntimeJobDag(); for (String job : jobs) { jobDag.addNode(job); } return jobDag; } private void emptyJobSets() { actualJobs = new HashSet<>(); expectedJobs = new HashSet<>(); } }
9,607
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestBatchAddJobs.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.common.ZkTestBase; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobDag; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.tools.ClusterSetup; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestBatchAddJobs extends ZkTestBase { private static final String CLUSTER_NAME = CLUSTER_PREFIX + "_TestBatchAddJobs"; private static final String QUEUE_NAME = "TestBatchAddJobQueue"; private ClusterSetup _setupTool; private List<SubmitJobTask> _submitJobTasks; @BeforeClass public void beforeClass() { _setupTool = new ClusterSetup(ZK_ADDR); _setupTool.addCluster(CLUSTER_NAME, true); _submitJobTasks = new ArrayList<>(); } @Test public void testBatchAddJobs() throws Exception { TaskDriver driver = new TaskDriver(_gZkClient, CLUSTER_NAME); driver.createQueue(new JobQueue.Builder(QUEUE_NAME).build()); for (int i = 0; i < 10; i++) { _submitJobTasks.add(new SubmitJobTask(ZK_ADDR, i)); _submitJobTasks.get(i).start(); } WorkflowConfig workflowConfig = driver.getWorkflowConfig(QUEUE_NAME); while (workflowConfig.getJobDag().getAllNodes().size() < 100) { Thread.sleep(50); driver.getWorkflowConfig(QUEUE_NAME); } JobDag dag = workflowConfig.getJobDag(); String currentJob = dag.getAllNodes().iterator().next(); while (dag.getDirectChildren(currentJob).size() > 0) { String childJob = dag.getDirectChildren(currentJob).iterator().next(); if (!getPrefix(currentJob).equals(getPrefix(childJob)) && currentJob.charAt(currentJob.length() - 1) != '9') { Assert.fail(); } currentJob = childJob; } } private String getPrefix(String job) { return job.split("#")[0]; } @AfterClass public void afterClass() { for (SubmitJobTask submitJobTask : _submitJobTasks) { submitJobTask.interrupt(); submitJobTask.cleanup(); } deleteCluster(CLUSTER_NAME); } static class SubmitJobTask extends Thread { private TaskDriver _driver; private String _jobPrefixName; private HelixManager _manager; public SubmitJobTask(String zkAddress, int index) throws Exception { _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Administrator", InstanceType.ADMINISTRATOR, zkAddress); _manager.connect(); _driver = new TaskDriver(_manager); _jobPrefixName = "JOB_" + index + "#"; } @Override public void start() { List<String> jobNames = new ArrayList<>(); List<JobConfig.Builder> jobConfigBuilders = new ArrayList<>(); for (int i = 0; i < 10; i++) { String jobName = _jobPrefixName + i; jobNames.add(jobName); jobConfigBuilders.add(new JobConfig.Builder().addTaskConfigs(Collections .singletonList(new TaskConfig("CMD", null, UUID.randomUUID().toString(), "TARGET")))); } _driver.enqueueJobs(QUEUE_NAME, jobNames, jobConfigBuilders); } public void cleanup() { _manager.disconnect(); } } }
9,608
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestUpdateWorkflow.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.Calendar; import java.util.concurrent.TimeUnit; import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.ScheduleConfig; import org.apache.helix.task.TargetState; import org.apache.helix.task.TaskState; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; public class TestUpdateWorkflow extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestUpdateWorkflow.class); @Test public void testUpdateRunningQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue queue = createDefaultRecurrentJobQueue(queueName, 2); _driver.start(queue); WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); WorkflowConfig workflowConfig = _driver.getWorkflowConfig(queueName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowConfig); Calendar startTime = Calendar.getInstance(); startTime.set(Calendar.SECOND, startTime.get(Calendar.SECOND) + 1); ScheduleConfig scheduleConfig = ScheduleConfig.recurringFromDate(startTime.getTime(), TimeUnit.MINUTES, 2); configBuilder.setScheduleConfig(scheduleConfig); // ensure current schedule is started String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); _driver.pollForWorkflowState(scheduledQueue, TaskState.IN_PROGRESS); _driver.updateWorkflow(queueName, configBuilder.build()); // ensure current schedule is completed _driver.pollForWorkflowState(scheduledQueue, TaskState.COMPLETED); // Make sure next round of the recurrent workflow is scheduled Assert .assertTrue(TestHelper.verify(() -> (TaskTestUtil.pollForWorkflowContext(_driver, queueName) .getScheduledWorkflows().size() > 1), TestHelper.WAIT_DURATION)); wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); WorkflowConfig wCfg = _driver.getWorkflowConfig(scheduledQueue); Calendar configStartTime = Calendar.getInstance(); configStartTime.setTime(wCfg.getStartTime()); Assert.assertTrue( (startTime.get(Calendar.HOUR_OF_DAY) == configStartTime.get(Calendar.HOUR_OF_DAY) && startTime.get(Calendar.MINUTE) == configStartTime.get(Calendar.MINUTE) && startTime.get(Calendar.SECOND) == configStartTime.get(Calendar.SECOND))); } @Test public void testUpdateStoppedQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue queue = createDefaultRecurrentJobQueue(queueName, 2); _driver.start(queue); WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); // ensure current schedule is started String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); _driver.pollForWorkflowState(scheduledQueue, TaskState.IN_PROGRESS); _driver.stop(queueName); WorkflowConfig workflowConfig = _driver.getWorkflowConfig(queueName); Assert.assertEquals(workflowConfig.getTargetState(), TargetState.STOP); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowConfig); Calendar startTime = Calendar.getInstance(); startTime.set(Calendar.SECOND, startTime.get(Calendar.SECOND) + 1); ScheduleConfig scheduleConfig = ScheduleConfig.recurringFromDate(startTime.getTime(), TimeUnit.MINUTES, 2); configBuilder.setScheduleConfig(scheduleConfig); _driver.updateWorkflow(queueName, configBuilder.build()); workflowConfig = _driver.getWorkflowConfig(queueName); Assert.assertEquals(workflowConfig.getTargetState(), TargetState.STOP); _driver.resume(queueName); // ensure current schedule is completed _driver.pollForWorkflowState(scheduledQueue, TaskState.COMPLETED); // Make sure next round of the recurrent workflow is scheduled Assert .assertTrue(TestHelper.verify(() -> (TaskTestUtil.pollForWorkflowContext(_driver, queueName) .getScheduledWorkflows().size() > 1), TestHelper.WAIT_DURATION)); wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); WorkflowConfig wCfg = _driver.getWorkflowConfig(scheduledQueue); Calendar configStartTime = Calendar.getInstance(); configStartTime.setTime(wCfg.getStartTime()); Assert.assertTrue( (startTime.get(Calendar.HOUR_OF_DAY) == configStartTime.get(Calendar.HOUR_OF_DAY) && startTime.get(Calendar.MINUTE) == configStartTime.get(Calendar.MINUTE) && startTime.get(Calendar.SECOND) == configStartTime.get(Calendar.SECOND))); } private JobQueue createDefaultRecurrentJobQueue(String queueName, int numJobs) { JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName, 0, 600000); for (int i = 0; i <= numJobs; i++) { String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(targetPartition)); String jobName = targetPartition.toLowerCase() + "Job" + i; queueBuild.enqueueJob(jobName, jobConfig); } return queueBuild.build(); } }
9,609
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestRetrieveWorkflows.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.Test; public class TestRetrieveWorkflows extends TaskTestBase { @Test public void testGetAllWorkflows() throws Exception { List<Workflow> workflowList = new ArrayList<Workflow>(); for (int i = 0; i < 2; i++) { Workflow workflow = WorkflowGenerator .generateDefaultRepeatedJobWorkflowBuilder(TestHelper.getTestMethodName() + i).build(); _driver.start(workflow); workflowList.add(workflow); } for (Workflow workflow : workflowList) { _driver.pollForWorkflowState(workflow.getName(), TaskState.COMPLETED); } Map<String, WorkflowConfig> workflowConfigMap = _driver.getWorkflows(); Assert.assertEquals(workflowConfigMap.size(), workflowList.size()); for (Map.Entry<String, WorkflowConfig> workflow : workflowConfigMap.entrySet()) { WorkflowConfig workflowConfig = workflow.getValue(); WorkflowContext workflowContext = _driver.getWorkflowContext(workflow.getKey()); Assert.assertNotNull(workflowContext); for (String job : workflowConfig.getJobDag().getAllNodes()) { JobConfig jobConfig = _driver.getJobConfig(job); JobContext jobContext = _driver.getJobContext(job); Assert.assertNotNull(jobConfig); Assert.assertNotNull(jobContext); } } } }
9,610
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestAddDeleteTask.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.helix.HelixException; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.model.IdealState; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestAddDeleteTask extends TaskTestBase { private static final String DATABASE = "TestDB_" + TestHelper.getTestClassName(); @BeforeClass public void beforeClass() throws Exception { _numNodes = 3; super.beforeClass(); } @AfterClass public void afterClass() throws Exception { super.afterClass(); } @Test public void testAddDeleteTaskWorkflowMissing() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; TaskConfig task = new TaskConfig(null, null, null, null); try { _driver.addTask(workflowName, jobName, task); Assert.fail("Exception is expected because workflow config is missing"); } catch (IllegalArgumentException e) { // IllegalArgumentException Exception is expected because workflow config is missing } try { _driver.deleteTask(workflowName, jobName, task.getId()); Assert.fail("Exception is expected because workflow config is missing"); } catch (IllegalArgumentException e) { // IllegalArgumentException Exception is expected because workflow config is missing } } @Test(dependsOnMethods = "testAddDeleteTaskWorkflowMissing") public void testAddDeleteTaskJobMissing() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName); _driver.start(workflowBuilder1.build()); // Make sure workflow config and context have been created Assert.assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(workflowName); WorkflowContext context = _driver.getWorkflowContext(workflowName); return (config != null && context != null); }, TestHelper.WAIT_DURATION)); TaskConfig task = new TaskConfig(null, null, null, null); try { _driver.addTask(workflowName, jobName, task); Assert.fail("Exception is expected because job config is missing"); } catch (IllegalArgumentException e) { // IllegalArgumentException Exception is expected because job config is missing } try { _driver.deleteTask(workflowName, jobName, task.getId()); Assert.fail("Exception is expected because job config is missing"); } catch (IllegalArgumentException e) { // IllegalArgumentException Exception is expected because job config is missing } } @Test(dependsOnMethods = "testAddDeleteTaskJobMissing") public void testAddTaskToTargetedJob() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet("MASTER")).setNumConcurrentTasksPerInstance(100) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); // Make sure workflow config and context have been created Assert.assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(workflowName); WorkflowContext context = _driver.getWorkflowContext(workflowName); return (config != null && context != null); }, TestHelper.WAIT_DURATION)); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); TaskConfig task = new TaskConfig(null, null, null, null); try { _driver.addTask(workflowName, jobName, task); Assert.fail("Exception is expected because job is targeted"); } catch (HelixException e) { // Helix Exception is expected because job is targeted } _driver.stop(workflowName); } @Test(dependsOnMethods = "testAddTaskToTargetedJob") public void testAddTaskJobAndTaskCommand() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Make sure workflow config and context have been created Assert.assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(workflowName); WorkflowContext context = _driver.getWorkflowContext(workflowName); return (config != null && context != null); }, TestHelper.WAIT_DURATION)); TaskConfig task = new TaskConfig("dummy", null, null, null); try { _driver.addTask(workflowName, jobName, task); Assert.fail("Exception is expected because job and task both have command field"); } catch (HelixException e) { // Helix Exception is expected job config and new task have command field } _driver.stop(workflowName); } @Test(dependsOnMethods = "testAddTaskJobAndTaskCommand") public void testAddTaskJobNotRunning() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); // Make sure workflow config and context have been created Assert.assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(workflowName); WorkflowContext context = _driver.getWorkflowContext(workflowName); return (config != null && context != null); }, TestHelper.WAIT_DURATION)); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.COMPLETED); TaskConfig task = new TaskConfig(null, null, null, null); try { _driver.addTask(workflowName, jobName, task); Assert.fail("Exception is expected because job is not running"); } catch (HelixException e) { // Helix Exception is expected because job id not running } } @Test(dependsOnMethods = "testAddTaskJobNotRunning") public void testAddTaskWithNullConfig() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); // Make sure workflow config and context have been created Assert.assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(workflowName); WorkflowContext context = _driver.getWorkflowContext(workflowName); return (config != null && context != null); }, TestHelper.WAIT_DURATION)); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); try { _driver.addTask(workflowName, jobName, null); Assert.fail("Exception is expected because task config is null"); } catch (IllegalArgumentException e) { // IllegalArgumentException Exception is expected because task config is null } _driver.stop(workflowName); } @Test(dependsOnMethods = "testAddTaskWithNullConfig") public void testAddTaskSuccessfully() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Add short running task Map<String, String> newTaskConfig = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); TaskConfig task = new TaskConfig(null, newTaskConfig, null, null); _driver.addTask(workflowName, jobName, task); Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); TaskPartitionState state = jobContext.getPartitionState(1); return (jobContext != null && state == TaskPartitionState.COMPLETED); }, TestHelper.WAIT_DURATION)); _driver.stop(workflowName); } @Test(dependsOnMethods = "testAddTaskSuccessfully") public void testAddTaskTwice() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Add short running task Map<String, String> newTaskConfig = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); TaskConfig task = new TaskConfig(null, newTaskConfig, null, null); _driver.addTask(workflowName, jobName, task); try { _driver.addTask(workflowName, jobName, task); Assert.fail("Exception is expected because task is being added multiple times"); } catch (HelixException e) { // Helix Exception is expected because task is being added multiple times } Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); TaskPartitionState state = jobContext.getPartitionState(1); return (jobContext != null && state == TaskPartitionState.COMPLETED); }, TestHelper.WAIT_DURATION)); _driver.stop(workflowName); } @Test(dependsOnMethods = "testAddTaskTwice") public void testAddTaskToJobNotStarted() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setExecutionDelay(5000L).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); Assert.assertTrue(TestHelper.verify(() -> { WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); return (workflowContext != null && jobContext == null); }, TestHelper.WAIT_DURATION)); // Add short running task Map<String, String> newTaskConfig = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); TaskConfig task = new TaskConfig(null, newTaskConfig, null, null); _driver.addTask(workflowName, jobName, task); Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state = jobContext.getPartitionState(1); if (state == null) { return false; } return (state == TaskPartitionState.COMPLETED); }, TestHelper.WAIT_DURATION)); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); } @Test(dependsOnMethods = "testAddTaskToJobNotStarted") public void testAddTaskWorkflowAndJobNotStarted() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _controller.syncStop(); _driver.start(workflowBuilder1.build()); Assert.assertTrue(TestHelper.verify(() -> { WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); return (workflowContext == null && jobContext == null); }, TestHelper.WAIT_DURATION)); // Add short running task Map<String, String> newTaskConfig = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); TaskConfig task = new TaskConfig(null, newTaskConfig, null, null); _driver.addTask(workflowName, jobName, task); // Start the Controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); } @Test(dependsOnMethods = "testAddTaskWorkflowAndJobNotStarted") public void testDeleteNonExistedTask() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "9999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); String dummyID = "1234"; try { _driver.deleteTask(workflowName, jobName, dummyID); Assert.fail("Exception is expected because a task with such ID does not exists!"); } catch (IllegalArgumentException e) { // IllegalArgumentException Exception is expected because task with such ID does not exists } _driver.waitToStop(workflowName, TestHelper.WAIT_DURATION); } @Test(dependsOnMethods = "testDeleteNonExistedTask") public void testDeleteTaskFromJobNotStarted() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setExecutionDelay(500000L).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); Assert.assertTrue(TestHelper.verify(() -> { WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); return (workflowContext != null && jobContext == null); }, TestHelper.WAIT_DURATION)); // Add short running task Map<String, String> newTaskConfig = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); TaskConfig task = new TaskConfig(null, newTaskConfig, null, null); _driver.addTask(workflowName, jobName, task); JobConfig jobConfig = _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName)); // Make sure task has been added to the job config Assert.assertTrue(jobConfig.getMapConfigs().containsKey(task.getId())); _driver.deleteTask(workflowName, jobName, task.getId()); jobConfig = _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName)); // Make sure task has been removed from job config Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task.getId())); _driver.deleteAndWaitForCompletion(workflowName, TestHelper.WAIT_DURATION); } @Test(dependsOnMethods = "testDeleteTaskFromJobNotStarted") public void testAddAndDeleteTask() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Wait until initial task goes to RUNNING state Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state = jobContext.getPartitionState(0); if (state == null) { return false; } return (state == TaskPartitionState.RUNNING); }, TestHelper.WAIT_DURATION)); // Add new task Map<String, String> newTaskConfig = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); TaskConfig task = new TaskConfig(null, newTaskConfig, null, null); _driver.addTask(workflowName, jobName, task); // Wait until new task goes to RUNNING state Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state = jobContext.getPartitionState(1); if (state == null) { return false; } return (state == TaskPartitionState.RUNNING); }, TestHelper.WAIT_DURATION)); _driver.deleteTask(workflowName, jobName, task.getId()); JobConfig jobConfig = _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName)); // Make sure task has been removed from job config Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task.getId())); Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } return (!jobContext.getPartitionSet().contains(1)); }, TestHelper.WAIT_DURATION)); _driver.stop(workflowName); } @Test(dependsOnMethods = "testAddAndDeleteTask") public void testDeleteTaskAndJobCompleted() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "20000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Wait until initial task goes to RUNNING state Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state = jobContext.getPartitionState(0); if (state == null) { return false; } return (state == TaskPartitionState.RUNNING); }, TestHelper.WAIT_DURATION)); // Add new task Map<String, String> taskConfig1 = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Map<String, String> taskConfig2 = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); TaskConfig task1 = new TaskConfig(null, taskConfig1, null, null); TaskConfig task2 = new TaskConfig(null, taskConfig2, null, null); _driver.addTask(workflowName, jobName, task1); _driver.addTask(workflowName, jobName, task2); // Wait until new task goes to RUNNING state Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state1 = jobContext.getPartitionState(1); TaskPartitionState state2 = jobContext.getPartitionState(2); if (state1 == null && state2 == null) { return false; } return (state1 == TaskPartitionState.RUNNING && state2 == TaskPartitionState.RUNNING); }, TestHelper.WAIT_DURATION)); _driver.deleteTask(workflowName, jobName, task1.getId()); _driver.deleteTask(workflowName, jobName, task2.getId()); JobConfig jobConfig = _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName)); // Make sure task has been removed from job config Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task1.getId())); Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task2.getId())); Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } return (!jobContext.getPartitionSet().contains(1) && !jobContext.getPartitionSet().contains(2)); }, TestHelper.WAIT_DURATION)); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.COMPLETED); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); } @Test(dependsOnMethods = "testDeleteTaskAndJobCompleted") public void testDeleteMiddleTaskAndAdd() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "20000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Wait until initial task goes to RUNNING state Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state = jobContext.getPartitionState(0); if (state == null) { return false; } return (state == TaskPartitionState.RUNNING); }, TestHelper.WAIT_DURATION)); // Only one task (initial task) should be included in the job Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); return (jobContext.getPartitionSet().size() == 1); }, TestHelper.WAIT_DURATION)); // Add new tasks Map<String, String> taskConfig1 = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Map<String, String> taskConfig2 = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Map<String, String> taskConfig3 = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Map<String, String> taskConfig4 = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); TaskConfig task1 = new TaskConfig(null, taskConfig1, null, null); TaskConfig task2 = new TaskConfig(null, taskConfig2, null, null); TaskConfig task3 = new TaskConfig(null, taskConfig3, null, null); TaskConfig task4 = new TaskConfig(null, taskConfig4, null, null); _driver.addTask(workflowName, jobName, task1); _driver.addTask(workflowName, jobName, task2); _driver.addTask(workflowName, jobName, task3); _driver.addTask(workflowName, jobName, task4); // 5 tasks should be included in the job Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); return (jobContext.getPartitionSet().size() == 5); }, TestHelper.WAIT_DURATION)); // All Task should be in RUNNING Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); int runningTasks = 0; for (Integer pId: jobContext.getPartitionSet()) { if (jobContext.getPartitionState(pId) == TaskPartitionState.RUNNING) { runningTasks++; } } return (runningTasks == 5); }, TestHelper.WAIT_DURATION)); _driver.deleteTask(workflowName, jobName, task3.getId()); // Since one of the tasks had been delete, we should expect 4 tasks in the context Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); return (jobContext.getPartitionSet().size() == 4); }, TestHelper.WAIT_DURATION)); // Add new tasks and make sure the task is being added to context Map<String, String> taskConfig5 = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); TaskConfig task5 = new TaskConfig(null, taskConfig5, null, null); _driver.addTask(workflowName, jobName, task5); Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); return (jobContext.getPartitionSet().size() == 5); }, TestHelper.WAIT_DURATION)); _driver.stop(workflowName); } @Test(dependsOnMethods = "testDeleteTaskAndJobCompleted") public void testPartitionDropTargetedJob() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; _gSetupTool.addResourceToCluster(CLUSTER_NAME, DATABASE, 3, MASTER_SLAVE_STATE_MODEL, IdealState.RebalanceMode.SEMI_AUTO.name()); _gSetupTool.rebalanceResource(CLUSTER_NAME, DATABASE, 3); List<String> preferenceList = new ArrayList<>(); preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 0)); preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 1)); preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 2)); IdealState idealState = new IdealState(DATABASE); idealState.setPreferenceList(DATABASE + "_0", preferenceList); idealState.setPreferenceList(DATABASE + "_1", preferenceList); idealState.setPreferenceList(DATABASE + "_2", preferenceList); _gSetupTool.getClusterManagementTool().updateIdealState(CLUSTER_NAME, DATABASE, idealState); JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Wait until new task goes to RUNNING state Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state1 = jobContext.getPartitionState(0); TaskPartitionState state2 = jobContext.getPartitionState(1); TaskPartitionState state3 = jobContext.getPartitionState(2); if (state1 == null || state2 == null || state3 == null) { return false; } return (state1 == TaskPartitionState.RUNNING && state2 == TaskPartitionState.RUNNING && state3 == TaskPartitionState.RUNNING); }, TestHelper.WAIT_DURATION)); // Remove one partition from the IS idealState = new IdealState(DATABASE); idealState.setPreferenceList(DATABASE + "_1", preferenceList); _gSetupTool.getClusterManagementTool().removeFromIdealState(CLUSTER_NAME, DATABASE, idealState); Assert.assertTrue(TestHelper .verify(() -> ((_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getPartitionSet().size() == 2)), TestHelper.WAIT_DURATION)); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); } @Test(dependsOnMethods = "testPartitionDropTargetedJob") public void testAddDeleteTaskOneInstance() throws Exception { // Stop all participant other than participant 0 for (int i = 1; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(1).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); // Wait until initial task goes to RUNNING state Assert.assertTrue(TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)); if (jobContext == null) { return false; } TaskPartitionState state = jobContext.getPartitionState(0); if (state == null) { return false; } return (state == TaskPartitionState.RUNNING); }, TestHelper.WAIT_DURATION)); // Add new task Map<String, String> newTaskConfig = new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); TaskConfig task = new TaskConfig(null, newTaskConfig, null, null); _driver.addTask(workflowName, jobName, task); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getPartitionSet().size(), 2); // Since only one task is allowed per instance, the new task should be scheduled Assert.assertNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getPartitionState(1)); _driver.deleteTask(workflowName, jobName, task.getId()); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName)) .getPartitionSet().size(), 1); _driver.stop(workflowName); } }
9,611
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestRunJobsWithMissingTarget.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestRunJobsWithMissingTarget extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestRunJobsWithMissingTarget.class); @BeforeClass public void beforeClass() throws Exception { _numDbs = 5; super.beforeClass(); } @Test public void testJobFailsWithMissingTarget() throws Exception { String workflowName = TestHelper.getTestMethodName(); // Create a workflow LOG.info("Starting job-queue: " + workflowName); Workflow.Builder builder = new Workflow.Builder(workflowName); // Create and Enqueue jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource( _testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")); String jobName = "job" + _testDbs.get(i); builder.addJob(jobName, jobConfig); if (i > 0) { builder.addParentChildDependency("job" + _testDbs.get(i - 1), "job" + _testDbs.get(i)); } currentJobNames.add(jobName); } _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, _testDbs.get(1)); _driver.start(builder.build()); String namedSpaceJob = String.format("%s_%s", workflowName, currentJobNames.get(1)); _driver.pollForJobState(workflowName, namedSpaceJob, TaskState.FAILED); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); _driver.delete(workflowName); } @Test(dependsOnMethods = "testJobFailsWithMissingTarget") public void testJobContinueUponParentJobFailure() throws Exception { String workflowName = TestHelper.getTestMethodName(); // Create a workflow LOG.info("Starting job-queue: " + workflowName); Workflow.Builder builder = new Workflow.Builder(workflowName).setWorkflowConfig( new WorkflowConfig.Builder(workflowName).setFailureThreshold(10).build()); // Create and add jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")).setIgnoreDependentJobFailure(true); String jobName = "job" + _testDbs.get(i); builder.addJob(jobName, jobConfig); if (i > 0) { builder.addParentChildDependency("job" + _testDbs.get(i - 1), "job" + _testDbs.get(i)); } currentJobNames.add(jobName); } _driver.start(builder.build()); String namedSpaceJob1 = String.format("%s_%s", workflowName, currentJobNames.get(1)); _driver.pollForJobState(workflowName, namedSpaceJob1, TaskState.FAILED); String lastJob = String.format("%s_%s", workflowName, currentJobNames.get(currentJobNames.size() - 1)); _driver.pollForJobState(workflowName, lastJob, TaskState.COMPLETED); _driver.delete(workflowName); } @Test(dependsOnMethods = "testJobContinueUponParentJobFailure") public void testJobFailsWithMissingTargetInRunning() throws Exception { String workflowName = TestHelper.getTestMethodName(); // Create a workflow LOG.info("Starting job-queue: " + workflowName); Workflow.Builder builder = new Workflow.Builder(workflowName); // Create and add jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")); String jobName = "job" + _testDbs.get(i); builder.addJob(jobName, jobConfig); if (i > 0) { builder.addParentChildDependency("job" + _testDbs.get(i - 1), "job" + _testDbs.get(i)); } currentJobNames.add(jobName); } _driver.start(builder.build()); _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, _testDbs.get(0)); String namedSpaceJob1 = String.format("%s_%s", workflowName, currentJobNames.get(0)); _driver.pollForJobState(workflowName, namedSpaceJob1, TaskState.FAILED); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); _driver.delete(workflowName); } }
9,612
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestForceDeleteWorkflow.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.ImmutableMap; import org.apache.helix.HelixAdmin; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.IdealState; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This test checks the functionality of the ForceDelete in various conditions. */ public class TestForceDeleteWorkflow extends TaskTestBase { private static final long LONG_TIMEOUT = 200000L; // Three types of execution times have been considered in this test. private static final String SHORT_EXECUTION_TIME = "1000"; private static final String MEDIUM_EXECUTION_TIME = "10000"; private static final String LONG_EXECUTION_TIME = "100000"; // Long delay to simulate the tasks that are stuck in Task.cancel(). private static final String STOP_DELAY = "1000000"; // These AtomicIntegers are used to verify that the tasks are indeed stuck in Task.cancel(). // CANCEL shows that the task cancellation process has been started. (Incremented at the beginning // of Task.cancel()) // STOP shows that the task cancellation process has been finished. (Incremented at the end of // Task.cancel()) private static final AtomicInteger CANCEL_COUNT = new AtomicInteger(0); private static final AtomicInteger STOP_COUNT = new AtomicInteger(0); @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); // Stop participants that have been started in super class for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); } // Check that participants are actually stopped for (int i = 0; i < _numNodes; i++) { Assert.assertFalse(_participants[i].isConnected()); } // Start new participants that have new TaskStateModel (DelayedStopTask) information _participants = new MockParticipantManager[_numNodes]; for (int i = 0; i < _numNodes; i++) { Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(DelayedStopTask.TASK_COMMAND, DelayedStopTask::new); String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } } @Test public void testDeleteCompletedWorkflowForcefully() throws Exception { // Create a simple workflow and wait for its completion. Then delete the WorkflowContext and // WorkflowConfig using ForceDelete. String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = createCustomWorkflow(workflowName, SHORT_EXECUTION_TIME, "0"); _driver.start(builder.build()); // Wait until workflow is created and completed. _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); // Check that WorkflowConfig and WorkflowContext are indeed created for this workflow Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); // Stop the Controller _controller.syncStop(); _driver.delete(workflowName, true); // Check that WorkflowConfig and WorkflowContext are indeed deleted for this workflow. boolean isWorkflowDeleted = TestHelper.verify(() -> { WorkflowConfig wfcfg = _driver.getWorkflowConfig(workflowName); WorkflowContext wfctx = _driver.getWorkflowContext(workflowName); return (wfcfg == null && wfctx == null); }, 60 * 1000); Assert.assertTrue(isWorkflowDeleted); } @Test(dependsOnMethods = "testDeleteCompletedWorkflowForcefully") public void testDeleteRunningWorkflowForcefully() throws Exception { // Create a simple workflow and wait until it reaches the Running state. Then delete the // WorkflowContext and WorkflowConfig using ForceDelete. // Start the Controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = createCustomWorkflow(workflowName, LONG_EXECUTION_TIME, "0"); _driver.start(builder.build()); // Wait until workflow is created and running. _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); // Check the status of JOB0 to make sure it is running. _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "JOB0"), TaskState.IN_PROGRESS); // Check that WorkflowConfig and WorkflowContext are indeed created for this workflow Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); // Stop the Controller _controller.syncStop(); _driver.delete(workflowName, true); // Check that WorkflowConfig and WorkflowContext are indeed deleted for this workflow. boolean isWorkflowDeleted = TestHelper.verify(() -> { WorkflowConfig wfcfg = _driver.getWorkflowConfig(workflowName); WorkflowContext wfctx = _driver.getWorkflowContext(workflowName); return (wfcfg == null && wfctx == null); }, 60 * 1000); Assert.assertTrue(isWorkflowDeleted); } @Test(dependsOnMethods = "testDeleteRunningWorkflowForcefully") public void testDeleteStoppedWorkflowForcefully() throws Exception { // Create a simple workflow. Stop the workflow and wait until it's fully stopped. Then delete // the WorkflowContext and WorkflowConfig using ForceDelete. // Start the Controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = createCustomWorkflow(workflowName, MEDIUM_EXECUTION_TIME, "0"); _driver.start(builder.build()); // Wait until workflow is created and running. _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); _driver.stop(workflowName); // Wait until workflow is stopped. _driver.pollForWorkflowState(workflowName, TaskState.STOPPED); // Wait until workflow is stopped. Also, jobs should be either stopped or not created (null). boolean areJobsStopped = TestHelper.verify(() -> { WorkflowContext wCtx1 = _driver.getWorkflowContext(workflowName); TaskState job0 = wCtx1.getJobState(TaskUtil.getNamespacedJobName(workflowName, "JOB0")); TaskState job1 = wCtx1.getJobState(TaskUtil.getNamespacedJobName(workflowName, "JOB1")); TaskState job2 = wCtx1.getJobState(TaskUtil.getNamespacedJobName(workflowName, "JOB2")); return ((job0 == null || job0 == TaskState.STOPPED) && (job1 == null || job1 == TaskState.STOPPED) && (job2 == null || job2 == TaskState.STOPPED)); }, 60 * 1000); Assert.assertTrue(areJobsStopped); // Check that WorkflowConfig and WorkflowContext are indeed created for this workflow. Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); // Stop the Controller _controller.syncStop(); _driver.delete(workflowName, true); // Check that WorkflowConfig and WorkflowContext are indeed deleted for this workflow. boolean isWorkflowDeleted = TestHelper.verify(() -> { WorkflowConfig wfcfg = _driver.getWorkflowConfig(workflowName); WorkflowContext wfctx = _driver.getWorkflowContext(workflowName); return (wfcfg == null && wfctx == null); }, 60 * 1000); Assert.assertTrue(isWorkflowDeleted); } @Test(dependsOnMethods = "testDeleteStoppedWorkflowForcefully") public void testDeleteStoppingStuckWorkflowForcefully() throws Exception { // In this test, Stuck workflow indicates a workflow that is in STOPPING state (user requested // to stop the workflow), its JOBs are also in STOPPING state but the tasks are stuck (or taking // a long time to stop) in RUNNING state. // Reset the cancel and stop counts CANCEL_COUNT.set(0); STOP_COUNT.set(0); // Start the Controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = createCustomWorkflow(workflowName, LONG_EXECUTION_TIME, STOP_DELAY); _driver.start(builder.build()); // Wait until workflow is created and running. _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); _driver.stop(workflowName); // Wait until workflow is is in Stopping state. _driver.pollForWorkflowState(workflowName, TaskState.STOPPING); // Check the status of JOB0 to make sure it is stopping. _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "JOB0"), TaskState.STOPPING); // Since ConcurrentTasksPerInstance is set to be 1, the total number of CANCEL_COUNT is expected // to be equal to number of nodes boolean haveAllCancelsCalled = TestHelper.verify(() -> { return CANCEL_COUNT.get() == _numNodes; }, 60 * 1000); Assert.assertTrue(haveAllCancelsCalled); // Check that STOP_COUNT is 0. This checks that no tasks' Task.cancel() have returned, verifying // that they are indeed stuck. Assert.assertEquals(STOP_COUNT.get(), 0); Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); // Stop the Controller. _controller.syncStop(); _driver.delete(workflowName, true); // Check that WorkflowConfig and WorkflowContext are indeed deleted for this workflow. boolean isWorkflowDeleted = TestHelper.verify(() -> { WorkflowConfig wfcfg = _driver.getWorkflowConfig(workflowName); WorkflowContext wfctx = _driver.getWorkflowContext(workflowName); return (wfcfg == null && wfctx == null); }, 60 * 1000); Assert.assertTrue(isWorkflowDeleted); } private Workflow.Builder createCustomWorkflow(String workflowName, String executionTime, String stopDelay) { Workflow.Builder builder = new Workflow.Builder(workflowName); // Workflow Schematic: // JOB0 // /\ // / \ // JOB1 JOB2 JobConfig.Builder jobBuilder0 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setTimeoutPerTask(LONG_TIMEOUT).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, executionTime, DelayedStopTask.JOB_DELAY_CANCEL, stopDelay)); JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setTimeoutPerTask(LONG_TIMEOUT).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, executionTime, DelayedStopTask.JOB_DELAY_CANCEL, stopDelay)); JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setTimeoutPerTask(LONG_TIMEOUT).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, executionTime, DelayedStopTask.JOB_DELAY_CANCEL, stopDelay)); builder.addParentChildDependency("JOB0", "JOB1"); builder.addParentChildDependency("JOB0", "JOB2"); builder.addJob("JOB0", jobBuilder0); builder.addJob("JOB1", jobBuilder1); builder.addJob("JOB2", jobBuilder2); return builder; } /** * A mock task that extents MockTask class and delays cancellation of the tasks. */ private static class DelayedStopTask extends MockTask { private static final String JOB_DELAY_CANCEL = "DelayCancel"; private final long _delayCancel; DelayedStopTask(TaskCallbackContext context) { super(context); Map<String, String> cfg = context.getJobConfig().getJobCommandConfigMap(); if (cfg == null) { cfg = new HashMap<>(); } _delayCancel = cfg.containsKey(JOB_DELAY_CANCEL) ? Long.parseLong(cfg.get(JOB_DELAY_CANCEL)) : 0L; } @Override public void cancel() { // Increment the cancel count so we know cancel() has been called CANCEL_COUNT.incrementAndGet(); try { Thread.sleep(_delayCancel); } catch (InterruptedException e) { e.printStackTrace(); } super.cancel(); // Increment the stop count so we know cancel() has finished and returned STOP_COUNT.incrementAndGet(); } } }
9,613
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskRebalancerStopResume.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.helix.HelixDataAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobDag; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskConstants; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.apache.helix.tools.ClusterStateVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; public class TestTaskRebalancerStopResume extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestTaskRebalancerStopResume.class); private static final String JOB_RESOURCE = "SomeJob"; @Test public void stopAndResume() throws Exception { Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(100)); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(commandConfig); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(JOB_RESOURCE, jobBuilder).build(); LOG.info("Starting flow " + flow.getName()); _driver.start(flow); _driver.pollForWorkflowState(JOB_RESOURCE, TaskState.IN_PROGRESS); LOG.info("Pausing job"); _driver.stop(JOB_RESOURCE); _driver.pollForWorkflowState(JOB_RESOURCE, TaskState.STOPPED); LOG.info("Resuming job"); _driver.resume(JOB_RESOURCE); _driver.pollForWorkflowState(JOB_RESOURCE, TaskState.COMPLETED); } @Test public void stopAndResumeWorkflow() throws Exception { String workflow = "SomeWorkflow"; Workflow flow = WorkflowGenerator.generateDefaultRepeatedJobWorkflowBuilder(workflow).build(); LOG.info("Starting flow " + workflow); _driver.start(flow); _driver.pollForWorkflowState(workflow, TaskState.IN_PROGRESS); LOG.info("Pausing workflow"); _driver.stop(workflow); _driver.pollForWorkflowState(workflow, TaskState.STOPPED); LOG.info("Resuming workflow"); _driver.resume(workflow); _driver.pollForWorkflowState(workflow, TaskState.COMPLETED); } @Test public void stopAndResumeNamedQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue queue = new JobQueue.Builder(queueName).build(); _driver.createQueue(queue); // Enqueue jobs Set<String> master = Sets.newHashSet("MASTER"); JobConfig.Builder job1 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB).setTargetPartitionStates(master) .setJobCommandConfigMap(Collections.singletonMap(MockTask.JOB_DELAY, "200")); String job1Name = "masterJob"; LOG.info("Enqueuing job: " + job1Name); _driver.enqueueJob(queueName, job1Name, job1); Set<String> slave = Sets.newHashSet("SLAVE"); JobConfig.Builder job2 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB).setTargetPartitionStates(slave); String job2Name = "slaveJob"; LOG.info("Enqueuing job: " + job2Name); _driver.enqueueJob(queueName, job2Name, job2); String namespacedJob1 = String.format("%s_%s", queueName, job1Name); _driver.pollForJobState(queueName, namespacedJob1, TaskState.IN_PROGRESS); // stop job1 LOG.info("Pausing job-queue: " + queueName); _driver.stop(queueName); _driver.pollForJobState(queueName, namespacedJob1, TaskState.STOPPED); _driver.pollForWorkflowState(queueName, TaskState.STOPPED); // Ensure job2 is not started String namespacedJob2 = String.format("%s_%s", queueName, job2Name); TaskTestUtil.pollForEmptyJobState(_driver, queueName, job2Name); LOG.info("Resuming job-queue: " + queueName); _driver.resume(queueName); // Ensure successful completion _driver.pollForJobState(queueName, namespacedJob1, TaskState.COMPLETED); _driver.pollForJobState(queueName, namespacedJob2, TaskState.COMPLETED); JobContext masterJobContext = _driver.getJobContext(namespacedJob1); JobContext slaveJobContext = _driver.getJobContext(namespacedJob2); // Ensure correct ordering long job1Finish = masterJobContext.getFinishTime(); long job2Start = slaveJobContext.getStartTime(); Assert.assertTrue(job2Start >= job1Finish); // Flush queue and check cleanup LOG.info("Flusing job-queue: " + queueName); _driver.flushQueue(queueName); verifyJobDeleted(queueName, namespacedJob1); verifyJobDeleted(queueName, namespacedJob2); verifyJobNotInQueue(queueName, namespacedJob1); verifyJobNotInQueue(queueName, namespacedJob2); } @Test public void stopDeleteJobAndResumeNamedQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName); // Create and Enqueue jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i <= 4; i++) { String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(targetPartition)) .setJobCommandConfigMap(Collections.singletonMap(MockTask.JOB_DELAY, "200")); String jobName = targetPartition.toLowerCase() + "Job" + i; LOG.info("Enqueuing job: " + jobName); queueBuilder.enqueueJob(jobName, jobBuilder); currentJobNames.add(i, jobName); } _driver.createQueue(queueBuilder.build()); // ensure job 1 is started before deleting it String deletedJob1 = currentJobNames.get(0); String namedSpaceDeletedJob1 = String.format("%s_%s", queueName, deletedJob1); _driver.pollForJobState(queueName, namedSpaceDeletedJob1, TaskState.IN_PROGRESS); // stop the queue LOG.info("Pausing job-queue: " + queueName); _driver.stop(queueName); _driver.pollForJobState(queueName, namedSpaceDeletedJob1, TaskState.STOPPED); _driver.pollForWorkflowState(queueName, TaskState.STOPPED); // delete the in-progress job (job 1) and verify it being deleted _driver.deleteJob(queueName, deletedJob1); verifyJobDeleted(queueName, namedSpaceDeletedJob1); LOG.info("Resuming job-queue: " + queueName); _driver.resume(queueName); // ensure job 2 is started _driver.pollForJobState(queueName, String.format("%s_%s", queueName, currentJobNames.get(1)), TaskState.IN_PROGRESS); // stop the queue LOG.info("Pausing job-queue: " + queueName); _driver.stop(queueName); _driver.pollForJobState(queueName, String.format("%s_%s", queueName, currentJobNames.get(1)), TaskState.STOPPED); _driver.pollForWorkflowState(queueName, TaskState.STOPPED); // Ensure job 3 is not started before deleting it String deletedJob2 = currentJobNames.get(2); String namedSpaceDeletedJob2 = String.format("%s_%s", queueName, deletedJob2); TaskTestUtil.pollForEmptyJobState(_driver, queueName, namedSpaceDeletedJob2); // delete not-started job (job 3) and verify it being deleted _driver.deleteJob(queueName, deletedJob2); verifyJobDeleted(queueName, namedSpaceDeletedJob2); LOG.info("Resuming job-queue: " + queueName); _driver.resume(queueName); currentJobNames.remove(deletedJob1); currentJobNames.remove(deletedJob2); // add job 3 back JobConfig.Builder job = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet("SLAVE")); // the name here MUST be unique in order to avoid conflicts with the old job cached in // RuntimeJobDag String newJob = deletedJob2 + "_second"; LOG.info("Enqueuing job: " + newJob); _driver.enqueueJob(queueName, newJob, job); currentJobNames.add(newJob); // Ensure the jobs left are successful completed in the correct order long preJobFinish = 0; for (int i = 0; i < currentJobNames.size(); i++) { String namedSpaceJobName = String.format("%s_%s", queueName, currentJobNames.get(i)); _driver.pollForJobState(queueName, namedSpaceJobName, TaskState.COMPLETED); JobContext jobContext = _driver.getJobContext(namedSpaceJobName); long jobStart = jobContext.getStartTime(); Assert.assertTrue(jobStart >= preJobFinish); preJobFinish = jobContext.getFinishTime(); } TimeUnit.MILLISECONDS.sleep(2000); // Flush queue LOG.info("Flusing job-queue: " + queueName); _driver.flushQueue(queueName); // TODO: Use TestHelper.verify() instead of waiting here. TimeUnit.MILLISECONDS.sleep(2000); // verify the cleanup for (int i = 0; i < currentJobNames.size(); i++) { String namedSpaceJobName = String.format("%s_%s", queueName, currentJobNames.get(i)); verifyJobDeleted(queueName, namedSpaceJobName); verifyJobNotInQueue(queueName, namedSpaceJobName); } } @Test public void stopDeleteJobAndResumeRecurrentQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName); // Create and Enqueue jobs List<String> currentJobNames = new ArrayList<String>(); Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(200)); for (int i = 0; i <= 4; i++) { String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; JobConfig.Builder job = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(commandConfig).setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(targetPartition)); String jobName = targetPartition.toLowerCase() + "Job" + i; LOG.info("Enqueuing job: " + jobName); queueBuilder.enqueueJob(jobName, job); currentJobNames.add(i, jobName); } _driver.createQueue(queueBuilder.build()); WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); // ensure job 1 is started before deleting it String deletedJob1 = currentJobNames.get(0); String namedSpaceDeletedJob1 = String.format("%s_%s", scheduledQueue, deletedJob1); _driver.pollForJobState(scheduledQueue, namedSpaceDeletedJob1, TaskState.IN_PROGRESS); // stop the queue LOG.info("Pausing job-queue: " + scheduledQueue); _driver.stop(queueName); _driver.pollForJobState(scheduledQueue, namedSpaceDeletedJob1, TaskState.STOPPED); _driver.pollForWorkflowState(scheduledQueue, TaskState.STOPPED); // delete the in-progress job (job 1) and verify it being deleted _driver.deleteJob(queueName, deletedJob1); verifyJobDeleted(queueName, namedSpaceDeletedJob1); verifyJobDeleted(scheduledQueue, namedSpaceDeletedJob1); LOG.info("Resuming job-queue: " + queueName); _driver.resume(queueName); // ensure job 2 is started _driver.pollForJobState(scheduledQueue, String.format("%s_%s", scheduledQueue, currentJobNames.get(1)), TaskState.IN_PROGRESS); // stop the queue LOG.info("Pausing job-queue: " + queueName); _driver.stop(queueName); _driver.pollForJobState(scheduledQueue, String.format("%s_%s", scheduledQueue, currentJobNames.get(1)), TaskState.STOPPED); _driver.pollForWorkflowState(scheduledQueue, TaskState.STOPPED); // Ensure job 3 is not started before deleting it String deletedJob2 = currentJobNames.get(2); String namedSpaceDeletedJob2 = String.format("%s_%s", scheduledQueue, deletedJob2); TaskTestUtil.pollForEmptyJobState(_driver, scheduledQueue, namedSpaceDeletedJob2); // delete not-started job (job 3) and verify it being deleted _driver.deleteJob(queueName, deletedJob2); verifyJobDeleted(queueName, namedSpaceDeletedJob2); verifyJobDeleted(scheduledQueue, namedSpaceDeletedJob2); LOG.info("Resuming job-queue: " + queueName); _driver.resume(queueName); // Ensure the jobs left are successful completed in the correct order currentJobNames.remove(deletedJob1); currentJobNames.remove(deletedJob2); long preJobFinish = 0; for (int i = 0; i < currentJobNames.size(); i++) { String namedSpaceJobName = String.format("%s_%s", scheduledQueue, currentJobNames.get(i)); _driver.pollForJobState(scheduledQueue, namedSpaceJobName, TaskState.COMPLETED); JobContext jobContext = _driver.getJobContext(namedSpaceJobName); long jobStart = jobContext.getStartTime(); Assert.assertTrue(jobStart >= preJobFinish); preJobFinish = jobContext.getFinishTime(); } // verify the job is not there for the next recurrence of queue schedule } @Test public void deleteJobFromRecurrentQueueNotStarted() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName); List<JobConfig.Builder> jobs = new ArrayList<JobConfig.Builder>(); List<String> jobNames = new ArrayList<String>(); Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(200)); int JOB_COUNTS = 3; for (int i = 0; i < JOB_COUNTS; i++) { String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; String jobName = targetPartition.toLowerCase() + "Job" + i; JobConfig.Builder job = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(commandConfig).setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(targetPartition)); jobs.add(job); jobNames.add(jobName); } for (int i = 0; i < JOB_COUNTS - 1; i++) { queueBuilder.enqueueJob(jobNames.get(i), jobs.get(i)); } _driver.createQueue(queueBuilder.build()); String currentLastJob = jobNames.get(JOB_COUNTS - 2); WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); // ensure all jobs are finished String namedSpaceJob = String.format("%s_%s", scheduledQueue, currentLastJob); _driver.pollForJobState(scheduledQueue, namedSpaceJob, TaskState.COMPLETED); // enqueue the last job LOG.info("Enqueuing job: " + jobNames.get(JOB_COUNTS - 1)); _driver.enqueueJob(queueName, jobNames.get(JOB_COUNTS - 1), jobs.get(JOB_COUNTS - 1)); // remove the last job _driver.deleteJob(queueName, jobNames.get(JOB_COUNTS - 1)); // verify verifyJobDeleted(queueName, String.format("%s_%s", scheduledQueue, jobNames.get(JOB_COUNTS - 1))); } @Test public void stopAndDeleteQueue() throws Exception { final String queueName = TestHelper.getTestMethodName(); // Create a queue System.out.println("START " + queueName + " at " + new Date(System.currentTimeMillis())); WorkflowConfig wfCfg = new WorkflowConfig.Builder(queueName).setExpiry(2, TimeUnit.MINUTES).build(); JobQueue qCfg = new JobQueue.Builder(queueName).fromMap(wfCfg.getResourceConfigMap()).build(); _driver.createQueue(qCfg); // Enqueue 2 jobs Set<String> master = Sets.newHashSet("MASTER"); JobConfig.Builder job1 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB).setTargetPartitionStates(master); String job1Name = "masterJob"; LOG.info("Enqueuing job1: " + job1Name); _driver.enqueueJob(queueName, job1Name, job1); Set<String> slave = Sets.newHashSet("SLAVE"); JobConfig.Builder job2 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB).setTargetPartitionStates(slave); String job2Name = "slaveJob"; LOG.info("Enqueuing job2: " + job2Name); _driver.enqueueJob(queueName, job2Name, job2); String namespacedJob1 = String.format("%s_%s", queueName, job1Name); _driver.pollForJobState(queueName, namespacedJob1, TaskState.COMPLETED); String namespacedJob2 = String.format("%s_%s", queueName, job2Name); _driver.pollForJobState(queueName, namespacedJob2, TaskState.COMPLETED); // Stop queue _driver.stop(queueName); boolean result = ClusterStateVerifier.verifyByPolling( new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME)); Assert.assertTrue(result); // Delete queue _driver.delete(queueName); // Wait until all status are cleaned up result = TestHelper.verify(new TestHelper.Verifier() { @Override public boolean verify() throws Exception { HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); // check paths for resource-config, ideal-state, external-view, property-store List<String> paths = Lists.newArrayList(keyBuilder.resourceConfigs().getPath(), keyBuilder.idealStates().getPath(), keyBuilder.externalViews().getPath(), PropertyPathBuilder.propertyStore(CLUSTER_NAME) + TaskConstants.REBALANCER_CONTEXT_ROOT); for (String path : paths) { List<String> childNames = accessor.getBaseDataAccessor().getChildNames(path, 0); for (String childName : childNames) { if (childName.startsWith(queueName)) { return false; } } } return true; } }, 30 * 1000); Assert.assertTrue(result); System.out.println("END " + queueName + " at " + new Date(System.currentTimeMillis())); } @Test public void testStopWorkflowInStoppingState() throws InterruptedException { final String workflowName = TestHelper.getTestMethodName(); // Create a workflow Workflow.Builder builder = new Workflow.Builder(workflowName); // Add 2 jobs Map<String, String> jobCommandConfigMap = new HashMap<String, String>(); jobCommandConfigMap.put(MockTask.JOB_DELAY, "1000000"); jobCommandConfigMap.put(MockTask.NOT_ALLOW_TO_CANCEL, String.valueOf(true)); List<TaskConfig> taskConfigs = ImmutableList.of( new TaskConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTaskId("testTask").build()); JobConfig.Builder job1 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .addTaskConfigs(taskConfigs).setJobCommandConfigMap(jobCommandConfigMap); String job1Name = "Job1"; JobConfig.Builder job2 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).addTaskConfigs(taskConfigs); String job2Name = "Job2"; builder.addJob(job1Name, job1); builder.addJob(job2Name, job2); _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, job1Name), TaskState.IN_PROGRESS); _driver.stop(workflowName); _driver.pollForWorkflowState(workflowName, TaskState.STOPPING); // Expect job and workflow stuck in STOPPING state. WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName); Assert.assertEquals( workflowContext.getJobState(TaskUtil.getNamespacedJobName(workflowName, job1Name)), TaskState.STOPPING); } private void verifyJobDeleted(String queueName, String jobName) throws Exception { HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Assert.assertNull(accessor.getProperty(keyBuilder.idealStates(jobName)), jobName + "'s idealstate has not been deleted!"); Assert.assertNull(accessor.getProperty(keyBuilder.resourceConfig(jobName)), jobName + "'s resourceConfig has not been deleted!"); TaskTestUtil.pollForEmptyJobState(_driver, queueName, jobName); } private void verifyJobNotInQueue(String queueName, String namedSpacedJobName) { WorkflowConfig workflowCfg = _driver.getWorkflowConfig(queueName); JobDag dag = workflowCfg.getJobDag(); Assert.assertFalse(dag.getAllNodes().contains(namedSpacedJobName)); Assert.assertFalse(dag.getChildrenToParents().containsKey(namedSpacedJobName)); Assert.assertFalse(dag.getParentsToChildren().containsKey(namedSpacedJobName)); } }
9,614
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobTimeoutTaskNotStarted.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.Map; import com.google.common.collect.Sets; import org.apache.helix.ConfigAccessor; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.mock.statemodel.MockTaskStateModelFactory; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.Task; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskSynchronizedTestBase; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestJobTimeoutTaskNotStarted extends TaskSynchronizedTestBase { @BeforeClass public void beforeClass() throws Exception { _numDbs = 1; _numNodes = 1; _numPartitions = 50; _numReplicas = 1; _participants = new MockParticipantManager[_numNodes]; _gSetupTool.addCluster(CLUSTER_NAME, true); setupParticipants(); setupDBs(); startParticipantsWithStuckTaskStateModelFactory(); createManagers(); _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); // Enable cancellation ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient); ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME); clusterConfig.stateTransitionCancelEnabled(true); clusterConfig.setMaxConcurrentTaskPerInstance(_numPartitions); _configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling(10000, 100)); } protected void startParticipantsWithStuckTaskStateModelFactory() { Map<String, TaskFactory> taskFactoryReg = new HashMap<String, TaskFactory>(); taskFactoryReg.put(MockTask.TASK_COMMAND, new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new MockTask(context); } }); // start dummy participants for (int i = 0; i < _numNodes; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new MockTaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } } @Test public void testTaskNotStarted() throws InterruptedException { final String BLOCK_WORKFLOW_NAME = "blockWorkflow"; final String TIMEOUT_WORKFLOW_NAME = "timeoutWorkflow"; final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB; final String TIMEOUT_JOB_1 = "timeoutJob1"; final String TIMEOUT_JOB_2 = "timeoutJob2"; // 50 blocking tasks JobConfig.Builder blockJobBuilder = new JobConfig.Builder().setWorkflow(BLOCK_WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setNumConcurrentTasksPerInstance(_numPartitions); Workflow.Builder blockWorkflowBuilder = new Workflow.Builder(BLOCK_WORKFLOW_NAME).addJob("blockJob", blockJobBuilder); _driver.start(blockWorkflowBuilder.build()); int numOfParticipantThreads = 40; Assert.assertTrue(TaskTestUtil.pollForAllTasksBlock(_manager.getHelixDataAccessor(), _participants[0].getInstanceName(), numOfParticipantThreads, 10000)); // Now, the HelixTask threadpool is full and blocked by blockJob. // New tasks assigned to the instance won't be assigned at all. // 2 timeout jobs, first one timeout, but won't block the second one to run, the second one also // timeout. JobConfig.Builder timeoutJobBuilder = new JobConfig.Builder().setWorkflow(TIMEOUT_WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setNumConcurrentTasksPerInstance(_numPartitions) .setTimeout(3000); // Wait a bit so that tasks are already assigned to the job (and will // be cancelled) WorkflowConfig.Builder timeoutWorkflowConfigBuilder = new WorkflowConfig.Builder(TIMEOUT_WORKFLOW_NAME).setFailureThreshold(1); // workflow // ignores first // job's timeout // and schedule // second job and // succeed. Workflow.Builder timeoutWorkflowBuilder = new Workflow.Builder(TIMEOUT_WORKFLOW_NAME) .setWorkflowConfig(timeoutWorkflowConfigBuilder.build()) .addJob(TIMEOUT_JOB_1, timeoutJobBuilder); // job 1 timeout, but won't block job 2 timeoutJobBuilder.setIgnoreDependentJobFailure(true); // ignore first job's timeout timeoutWorkflowBuilder.addJob(TIMEOUT_JOB_2, timeoutJobBuilder) // job 2 also timeout .addParentChildDependency(TIMEOUT_JOB_1, TIMEOUT_JOB_2); _driver.start(timeoutWorkflowBuilder.build()); _driver.pollForJobState(TIMEOUT_WORKFLOW_NAME, TaskUtil.getNamespacedJobName(TIMEOUT_WORKFLOW_NAME, TIMEOUT_JOB_1), TaskState.TIMED_OUT); _driver.pollForJobState(TIMEOUT_WORKFLOW_NAME, TaskUtil.getNamespacedJobName(TIMEOUT_WORKFLOW_NAME, TIMEOUT_JOB_2), TaskState.TIMED_OUT); _driver.pollForWorkflowState(TIMEOUT_WORKFLOW_NAME, TaskState.FAILED); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(TIMEOUT_WORKFLOW_NAME, TIMEOUT_JOB_1)); for (int pId : jobContext.getPartitionSet()) { if (jobContext.getAssignedParticipant(pId) != null) { // All tasks stuck at INIT->RUNNING, and state transition cancelled and marked TASK_ABORTED Assert.assertEquals(jobContext.getPartitionState(pId), TaskPartitionState.TASK_ABORTED); } } jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(TIMEOUT_WORKFLOW_NAME, TIMEOUT_JOB_2)); for (int pId : jobContext.getPartitionSet()) { if (jobContext.getAssignedParticipant(pId) != null) { // All tasks stuck at INIT->RUNNING, and state transition cancelled and marked TASK_ABORTED Assert.assertEquals(jobContext.getPartitionState(pId), TaskPartitionState.TASK_ABORTED); } } } }
9,615
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailureDependence.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.WorkflowConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestJobFailureDependence extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestJobFailureDependence.class); @BeforeClass public void beforeClass() throws Exception { _numDbs = 5; super.beforeClass(); } @Test public void testJobDependantFailure() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName, 0, 100); // Create and Enqueue jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")); String jobName = "job" + _testDbs.get(i); queueBuilder.enqueueJob(jobName, jobConfig); currentJobNames.add(jobName); } _driver.start(queueBuilder.build()); _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, _testDbs.get(2)); // all jobs after failed job should fail too. for (int i = 2; i < _numDbs; i++) { String namedSpaceJob = String.format("%s_%s", queueName, currentJobNames.get(i)); _driver.pollForJobState(queueName, namedSpaceJob, TaskState.FAILED); } } @Test public void testJobDependantWorkflowFailure() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName); // Create and Enqueue jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")); String jobName = "job" + _testDbs.get(i); queueBuilder.enqueueJob(jobName, jobConfig); currentJobNames.add(jobName); } _driver.start(queueBuilder.build()); _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, _testDbs.get(2)); String namedSpaceJob1 = String.format("%s_%s", queueName, currentJobNames.get(2)); _driver.pollForJobState(queueName, namedSpaceJob1, TaskState.FAILED); } @Test public void testIgnoreJobDependantFailure() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName, 0, 100); // Create and Enqueue jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")).setIgnoreDependentJobFailure(true); String jobName = "job" + _testDbs.get(i); queueBuilder.enqueueJob(jobName, jobConfig); currentJobNames.add(jobName); } _driver.start(queueBuilder.build()); _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, _testDbs.get(2)); String namedSpaceJob2 = String.format("%s_%s", queueName, currentJobNames.get(2)); _driver.pollForJobState(queueName, namedSpaceJob2, TaskState.FAILED); // all jobs after failed job should complete. for (int i = 3; i < _numDbs; i++) { String namedSpaceJob = String.format("%s_%s", queueName, currentJobNames.get(i)); _driver.pollForJobState(queueName, namedSpaceJob, TaskState.COMPLETED); } } @Test public void testWorkflowFailureJobThreshold() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName, 0, 3); // Create and Enqueue jobs List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")).setIgnoreDependentJobFailure(true); String jobName = "job" + _testDbs.get(i); queueBuilder.enqueueJob(jobName, jobConfig); currentJobNames.add(jobName); } _driver.start(queueBuilder.build()); _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, _testDbs.get(1)); String namedSpaceJob1 = String.format("%s_%s", queueName, currentJobNames.get(1)); _driver.pollForJobState(queueName, namedSpaceJob1, TaskState.FAILED); String lastJob = String.format("%s_%s", queueName, currentJobNames.get(currentJobNames.size() - 1)); _driver.pollForJobState(queueName, lastJob, TaskState.COMPLETED); _driver.flushQueue(queueName); WorkflowConfig currentWorkflowConfig = _driver.getWorkflowConfig(queueName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(currentWorkflowConfig); configBuilder.setFailureThreshold(0); _driver.updateWorkflow(queueName, configBuilder.build()); _driver.stop(queueName); for (int i = 0; i < _numDbs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE")).setIgnoreDependentJobFailure(true); String jobName = "job" + _testDbs.get(i); queueBuilder.enqueueJob(jobName, jobConfig); _driver.enqueueJob(queueName, jobName, jobConfig); } _driver.resume(queueName); namedSpaceJob1 = String.format("%s_%s", queueName, currentJobNames.get(1)); _driver.pollForJobState(queueName, namedSpaceJob1, TaskState.FAILED); } }
9,616
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskQuotaCalculations.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; public class TestTaskQuotaCalculations extends TaskTestBase { private CountDownLatch latch = new CountDownLatch(1); @BeforeClass public void beforeClass() throws Exception { _numNodes = 2; _numPartitions = 100; super.beforeClass(); // Stop participants that have been started in super class for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } _participants = new MockParticipantManager[_numNodes]; // Start first participant startParticipantAndRegisterNewMockTask(0); } @AfterClass public void afterClass() throws Exception { super.afterClass(); } @Test public void testStuckTaskQuota() throws Exception { String workflowName1 = TestHelper.getTestMethodName() + "_1"; String workflowName2 = TestHelper.getTestMethodName() + "_2"; String workflowName3 = TestHelper.getTestMethodName() + "_3"; String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName1).setNumberOfTasks(40) .setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); JobConfig.Builder jobBuilder2 = new JobConfig.Builder().setWorkflow(workflowName2) .setNumberOfTasks(1).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); JobConfig.Builder jobBuilder3 = new JobConfig.Builder().setWorkflow(workflowName3) .setNumberOfTasks(1).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName1).addJob(jobName, jobBuilder1); Workflow.Builder workflowBuilder2 = new Workflow.Builder(workflowName2).addJob(jobName, jobBuilder2); Workflow.Builder workflowBuilder3 = new Workflow.Builder(workflowName3).addJob(jobName, jobBuilder3); _driver.start(workflowBuilder1.build()); // Make sure the JOB0 of workflow1 is started and all of the tasks are assigned to the // participant 0 _driver.pollForJobState(workflowName1, TaskUtil.getNamespacedJobName(workflowName1, jobName), TaskState.IN_PROGRESS); String participant0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); for (int i = 0; i < 40; i++) { int finalI = i; Assert.assertTrue(TestHelper.verify(() -> (TaskPartitionState.RUNNING .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName1, jobName)) .getPartitionState(finalI)) && participant0 .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName1, jobName)) .getAssignedParticipant(finalI))), TestHelper.WAIT_DURATION)); } // Start the second participant startParticipantAndRegisterNewMockTask(1); _driver.start(workflowBuilder2.build()); // Make sure the JOB0 of workflow2 is started and the only task of this job is assigned to // participant1 _driver.pollForJobState(workflowName2, TaskUtil.getNamespacedJobName(workflowName2, jobName), TaskState.IN_PROGRESS); String participant1 = PARTICIPANT_PREFIX + "_" + (_startPort + 1); Assert.assertTrue(TestHelper.verify(() -> (TaskPartitionState.RUNNING.equals(_driver .getJobContext(TaskUtil.getNamespacedJobName(workflowName2, jobName)).getPartitionState(0)) && participant1 .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName2, jobName)) .getAssignedParticipant(0))), TestHelper.WAIT_DURATION)); // Delete the workflow1 _driver.delete(workflowName1); // Since the tasks will be stuck for workflow1 after the deletion, the participant 0 is out of // capacity. Hence, the new tasks should be assigned to participant 1 _driver.start(workflowBuilder3.build()); // Make sure the JOB0 of workflow3 is started and the only task of this job is assigned to // participant1 _driver.pollForJobState(workflowName3, TaskUtil.getNamespacedJobName(workflowName3, jobName), TaskState.IN_PROGRESS); Assert.assertTrue(TestHelper .verify(() -> (TaskPartitionState.RUNNING .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName3, jobName)) .getPartitionState(0))), TestHelper.WAIT_DURATION) && participant1 .equals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName3, jobName)) .getAssignedParticipant(0))); latch.countDown(); // Stop the workflow2 and workflow3 _driver.stop(workflowName2); _driver.stop(workflowName3); } @Test(dependsOnMethods = "testStuckTaskQuota") public void testTaskErrorMaxRetriesQuotaRelease() throws Exception { for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } _participants = new MockParticipantManager[_numNodes]; // Start only one participant startParticipantAndRegisterNewMockTask(0); String jobQueueName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(2).setWorkflow(jobQueueName).setFailureThreshold(100000) .setJobCommandConfigMap( ImmutableMap.of(MockTask.JOB_DELAY, "10", MockTask.FAILURE_COUNT_BEFORE_SUCCESS, "10")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob(jobName, jobBuilder); _driver.start(jobQueue.build()); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, jobName), TaskState.COMPLETED); } private void startParticipantAndRegisterNewMockTask(int participantIndex) { Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(NewMockTask.TASK_COMMAND, NewMockTask::new); String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + participantIndex); _participants[participantIndex] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[participantIndex].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[participantIndex], taskFactoryReg)); _participants[participantIndex].syncStart(); } /** * A mock task that extents MockTask class to count the number of cancel messages. */ private class NewMockTask extends MockTask { NewMockTask(TaskCallbackContext context) { super(context); } @Override public void cancel() { try { latch.await(); } catch (Exception e) { // Pass } super.cancel(); } } }
9,617
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskRebalancerRetryLimit.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.Test; /** * Test task will be retried up to MaxAttemptsPerTask {@see HELIX-562} */ public class TestTaskRebalancerRetryLimit extends TaskTestBase { @Test public void test() throws Exception { String jobResource = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG) .setMaxAttemptsPerTask(2).setCommand(MockTask.TASK_COMMAND) .setFailureThreshold(Integer.MAX_VALUE) .setJobCommandConfigMap(ImmutableMap.of(MockTask.THROW_EXCEPTION, "true")); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait until the job completes. _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(jobResource)); for (int i = 0; i < _numPartitions; i++) { TaskPartitionState state = ctx.getPartitionState(i); if (state != null) { Assert.assertEquals(state, TaskPartitionState.TASK_ERROR); Assert.assertEquals(ctx.getPartitionNumAttempts(i), 2); } } } }
9,618
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestRebalanceRunningTask.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashSet; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.ExternalView; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskSynchronizedTestBase; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public final class TestRebalanceRunningTask extends TaskSynchronizedTestBase { private final String JOB = "test_job"; private String WORKFLOW; private final String DATABASE = WorkflowGenerator.DEFAULT_TGT_DB; private final int _initialNumNodes = 1; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; _numNodes = 2; _numPartitions = 2; _numReplicas = 1; // only Master, no Slave _numDbs = 1; _gSetupTool.addCluster(CLUSTER_NAME, true); setupParticipants(); setupDBs(); createManagers(); _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); } @BeforeMethod public void beforeMethod() throws InterruptedException { // Added to make sure that jobs in each test fail/complete MockTask._signalFail = true; startParticipants(); Thread.sleep(1000); stopParticipants(); startParticipants(_initialNumNodes); Thread.sleep(1000); MockTask._signalFail = false; } @AfterMethod public void afterMethod() { stopParticipants(); MockTask._signalFail = false; } private boolean checkTasksOnDifferentInstances() { return new TaskTestUtil.Poller() { @Override public boolean check() { try { return getNumOfInstances() > 1; } catch (NullPointerException e) { return false; } } }.poll(); } private boolean checkTasksOnSameInstances() { return new TaskTestUtil.Poller() { @Override public boolean check() { try { return getNumOfInstances() == 1; } catch (NullPointerException e) { return false; } } }.poll(); } private int getNumOfInstances() { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW, JOB)); Set<String> instances = new HashSet<>(); for (int pId : jobContext.getPartitionSet()) { instances.add(jobContext.getAssignedParticipant(pId)); } return instances.size(); } /** * Task type: generic * Rebalance running task: disabled * Story: 1 node is down */ @Test public void testGenericTaskAndDisabledRebalanceAndNodeDown() throws InterruptedException { WORKFLOW = TestHelper.getTestMethodName(); startParticipant(_initialNumNodes); JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW).setNumberOfTasks(10) // should be enough for // consistent hashing to // place tasks on // different instances .setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); // task stuck Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW).addJob(JOB, jobBuilder); _driver.start(workflowBuilder.build()); Assert.assertTrue(checkTasksOnDifferentInstances()); // Stop a participant, tasks rebalanced to the same instance stopParticipant(_initialNumNodes); Assert.assertTrue(checkTasksOnSameInstances()); } /** * Task type: generic * Rebalance running task: disabled * Story: new node added, then current task fails */ @Test public void testGenericTaskAndDisabledRebalanceAndNodeAddedAndTaskFail() throws InterruptedException { WORKFLOW = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW) .setNumberOfTasks(10).setNumConcurrentTasksPerInstance(100) .setCommand(MockTask.TASK_COMMAND).setFailureThreshold(10).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); // task stuck Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW).addJob(JOB, jobBuilder); _driver.start(workflowBuilder.build()); // All tasks stuck on the same instance Assert.assertTrue(checkTasksOnSameInstances()); // Add a new instance startParticipant(_initialNumNodes); Thread.sleep(3000); // All tasks still stuck on the same instance, because RebalanceRunningTask is disabled Assert.assertTrue(checkTasksOnSameInstances()); // Signal to fail all tasks MockTask._signalFail = true; // After fail, some task will be re-assigned to the new node. // This doesn't require RebalanceRunningTask to be enabled Assert.assertTrue(checkTasksOnDifferentInstances()); } /** * Task type: generic * Rebalance running task: enabled * Story: new node added * NOTE: This test is disabled because this "load-balancing" would happen at the Task Assigner * level. In the legacy assignment strategy (Consistent Hashing) did not take instance's capacity * into account. However, the new quota-based scheduling takes capacity into account, and it will * generally assign to the most "free" instance, so load-balancing of tasks will happen at the * Assigner layer. Deprecating this test. */ @Deprecated @Test(enabled = false) public void testGenericTaskAndEnabledRebalanceAndNodeAdded() throws InterruptedException { WORKFLOW = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW) .setNumberOfTasks(10).setNumConcurrentTasksPerInstance(100) .setCommand(MockTask.TASK_COMMAND).setRebalanceRunningTask(true) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); // task stuck Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW).addJob(JOB, jobBuilder); _driver.start(workflowBuilder.build()); // All tasks stuck on the same instance Assert.assertTrue(checkTasksOnSameInstances()); // Add a new instance, and some running tasks will be rebalanced to the new node startParticipant(_initialNumNodes); Assert.assertTrue(checkTasksOnDifferentInstances()); } /** * Task type: fixed target * Rebalance running task: disabled * Story: 1 node is down */ @Test public void testFixedTargetTaskAndDisabledRebalanceAndNodeDown() throws InterruptedException { WORKFLOW = TestHelper.getTestMethodName(); startParticipant(_initialNumNodes); JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW).setTargetResource(DATABASE) .setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW).addJob(JOB, jobBuilder); _driver.start(workflowBuilder.build()); Assert.assertTrue(checkTasksOnDifferentInstances()); // Stop a participant and partitions will be moved to the same instance, // and tasks rebalanced accordingly stopParticipant(_initialNumNodes); Assert.assertTrue(checkTasksOnSameInstances()); } /** * Task type: fixed target * Rebalance running task: disabled * Story: new node added */ @Test public void testFixedTargetTaskAndDisabledRebalanceAndNodeAdded() throws Exception { WORKFLOW = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setNumConcurrentTasksPerInstance(100).setFailureThreshold(2).setMaxAttemptsPerTask(2) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); // task stuck Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW).addJob(JOB, jobBuilder); _driver.start(workflowBuilder.build()); // All tasks stuck on the same instance Assert.assertTrue(checkTasksOnSameInstances()); // Add a new instance, partition is rebalanced System.out.println("Start new participant"); startParticipant(_initialNumNodes); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setResources(Sets.newHashSet(DATABASE)) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verify(10 * 1000)); // Wait until master is switched to new instance and two masters exist on two different instances boolean isMasterOnTwoDifferentNodes = TestHelper.verify(() -> { Set<String> masterInstances = new HashSet<>(); ExternalView externalView = _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, DATABASE); if (externalView == null) { return false; } Map<String, String> stateMap0 = externalView.getStateMap(DATABASE + "_0"); Map<String, String> stateMap1 = externalView.getStateMap(DATABASE + "_1"); if (stateMap0 == null || stateMap1 == null) { return false; } for (Map.Entry<String, String> entry : stateMap0.entrySet()) { if (entry.getValue().equals("MASTER")) { masterInstances.add(entry.getKey()); } } for (Map.Entry<String, String> entry : stateMap1.entrySet()) { if (entry.getValue().equals("MASTER")) { masterInstances.add(entry.getKey()); } } return masterInstances.size() == 2; }, TestHelper.WAIT_DURATION); Assert.assertTrue(isMasterOnTwoDifferentNodes); // Running tasks are also rebalanced, even though RebalanceRunningTask is disabled Assert.assertTrue(checkTasksOnDifferentInstances()); } /** * Task type: fixed target * Rebalance running task: enabled * Story: new node added */ @Test public void testFixedTargetTaskAndEnabledRebalanceAndNodeAdded() throws InterruptedException { WORKFLOW = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setNumConcurrentTasksPerInstance(100).setRebalanceRunningTask(true) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); // task stuck Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW).addJob(JOB, jobBuilder); _driver.start(workflowBuilder.build()); // All tasks stuck on the same instance Assert.assertTrue(checkTasksOnSameInstances()); // Add a new instance, partition is rebalanced startParticipant(_initialNumNodes); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setResources(Sets.newHashSet(DATABASE)) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verify(10 * 1000)); // Running tasks are also rebalanced Assert.assertTrue(checkTasksOnDifferentInstances()); } }
9,619
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailureHighThreshold.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.HelixException; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskSynchronizedTestBase; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestJobFailureHighThreshold extends TaskSynchronizedTestBase { private static final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; _numDbs = 1; _numNodes = 1; _numPartitions = 5; _numReplicas = 1; _gSetupTool.addCluster(CLUSTER_NAME, true); setupParticipants(); setupDBs(); startParticipants(); createManagers(); _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling(10000, 100)); } /** * Number of instance is equal to number of failure threshold, thus job failure mechanism needs to * consider given up * tasks that no longer exist on the instance, not only given up tasks currently reported on * CurrentState. */ @Test public void testHighThreshold() throws InterruptedException { final String WORKFLOW_NAME = "testWorkflow"; final String JOB_NAME = "testJob"; JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap( ImmutableMap.of(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FATAL_FAILED.name())) .setFailureThreshold(1); Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW_NAME).addJob(JOB_NAME, jobBuilder); _driver.start(workflowBuilder.build()); _driver.pollForJobState(WORKFLOW_NAME, TaskUtil.getNamespacedJobName(WORKFLOW_NAME, JOB_NAME), TaskState.FAILED); _driver.pollForWorkflowState(WORKFLOW_NAME, TaskState.FAILED); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, JOB_NAME)); int countAborted = 0; int countNoState = 0; for (int pId : jobContext.getPartitionSet()) { TaskPartitionState state = jobContext.getPartitionState(pId); if (state == TaskPartitionState.TASK_ABORTED) { countAborted++; } else if (state == null) { countNoState++; } else { throw new HelixException(String.format("State %s is not expected.", state)); } } Assert.assertEquals(countAborted, 2); // Failure threshold is 1, so 2 tasks aborted. Assert.assertEquals(countNoState, 3); // Other 3 tasks are not scheduled at all. } }
9,620
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestNoDoubleAssign.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestNoDoubleAssign extends TaskTestBase { private static final int THREAD_COUNT = 10; private static final long CONNECTION_DELAY = 100L; private static final long POLL_DELAY = 50L; private static final String TASK_DURATION = "200"; private static final Random RANDOM = new Random(); private ScheduledExecutorService _executorServicePoll; private ScheduledExecutorService _executorServiceConnection; private AtomicBoolean _existsDoubleAssign = new AtomicBoolean(false); private Set<String> _jobNames = new HashSet<>(); @BeforeClass public void beforeClass() throws Exception { _numDbs = 0; _numPartitions = 0; _numReplicas = 0; super.beforeClass(); } /** * Tests that no Participants have more tasks from the same job than is specified in the config. * (MaxConcurrentTaskPerInstance, default value = 1) * NOTE: this test is supposed to generate a lot of Participant-side ERROR message (ZkClient * already closed!) because we are disconnecting them on purpose. */ @Test public void testNoDoubleAssign() throws InterruptedException { // Some arbitrary workload that creates a reasonably large amount of tasks int workload = 10; // Create a workflow with jobs and tasks String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); for (int i = 0; i < workload; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); for (int j = 0; j < workload; j++) { String taskID = "JOB_" + i + "_TASK_" + j; TaskConfig.Builder taskConfigBuilder = new TaskConfig.Builder(); taskConfigBuilder.setTaskId(taskID).setCommand(MockTask.TASK_COMMAND) .addConfig(MockTask.JOB_DELAY, TASK_DURATION); taskConfigs.add(taskConfigBuilder.build()); } String jobName = "JOB_" + i; _jobNames.add(workflowName + "_" + jobName); // Add the namespaced job name JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(10000) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG) .addTaskConfigs(taskConfigs).setIgnoreDependentJobFailure(true) .setFailureThreshold(100000) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, TASK_DURATION)); builder.addJob(jobName, jobBuilder); } // Start the workflow _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); breakConnection(); pollForDoubleAssign(); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); // Shut down thread pools _executorServicePoll.shutdown(); _executorServiceConnection.shutdown(); try { if (!_executorServicePoll.awaitTermination(180, TimeUnit.SECONDS)) { _executorServicePoll.shutdownNow(); } if (!_executorServiceConnection.awaitTermination(180, TimeUnit.SECONDS)) { _executorServiceConnection.shutdownNow(); } } catch (InterruptedException e) { _executorServicePoll.shutdownNow(); _executorServiceConnection.shutdownNow(); } Assert.assertFalse(_existsDoubleAssign.get()); } /** * Fetch the JobContext for all jobs in ZK and check that no two tasks are running on the same * Participant. */ private void pollForDoubleAssign() { _executorServicePoll = Executors.newScheduledThreadPool(THREAD_COUNT); _executorServicePoll.scheduleAtFixedRate(() -> { if (!_existsDoubleAssign.get()) { // Get JobContexts and test that they are assigned to disparate Participants for (String job : _jobNames) { JobContext jobContext = _driver.getJobContext(job); if (jobContext == null) { continue; } Set<String> instanceCache = new HashSet<>(); for (int partition : jobContext.getPartitionSet()) { if (jobContext.getPartitionState(partition) == TaskPartitionState.RUNNING) { String assignedParticipant = jobContext.getAssignedParticipant(partition); if (assignedParticipant != null) { if (instanceCache.contains(assignedParticipant)) { // Two tasks running on the same instance at the same time _existsDoubleAssign.set(true); return; } instanceCache.add(assignedParticipant); } } } } } }, 0L, POLL_DELAY, TimeUnit.MILLISECONDS); } /** * Randomly causes Participants to lost connection temporarily. */ private void breakConnection() { _executorServiceConnection = Executors.newScheduledThreadPool(THREAD_COUNT); _executorServiceConnection.scheduleAtFixedRate(() -> { synchronized (this) { int participantIndex = RANDOM.nextInt(_numNodes); stopParticipant(participantIndex); startParticipant(participantIndex); } }, 0L, CONNECTION_DELAY, TimeUnit.MILLISECONDS); } }
9,621
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskWithInstanceDisabled.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestTaskWithInstanceDisabled extends TaskTestBase { @Override @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); _numNodes = 2; _numReplicas = 2; _partitionVary = false; super.beforeClass(); } @Test public void testTaskWithInstanceDisabled() throws InterruptedException { _gSetupTool.getClusterManagementTool() .enableInstance(CLUSTER_NAME, PARTICIPANT_PREFIX + "_" + (_startPort + 0), false); String jobResource = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(jobResource)); Assert.assertEquals(ctx.getAssignedParticipant(0), PARTICIPANT_PREFIX + "_" + (_startPort + 1)); } }
9,622
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestEnqueueJobs.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestEnqueueJobs extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); } @Test public void testJobQueueAddingJobsOneByOne() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder().setWorkflowId(queueName).setParallelJobs(1); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); _driver.enqueueJob(queueName, "JOB0", jobBuilder); for (int i = 1; i < 5; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + (i - 1)), 10000L, TaskState.COMPLETED); _driver.waitToStop(queueName, 5000L); _driver.enqueueJob(queueName, "JOB" + i, jobBuilder); _driver.resume(queueName); } _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); } @Test public void testJobQueueAddingJobsAtSametime() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder().setWorkflowId(queueName).setParallelJobs(1); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); // Adding jobs JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); List<String> jobNames = new ArrayList<>(); List<JobConfig.Builder> jobBuilders = new ArrayList<>(); _driver.waitToStop(queueName, 5000L); for (int i = 0; i < 5; i++) { jobNames.add("JOB" + i); jobBuilders.add(jobBuilder); } // Add jobs as batch to the queue _driver.enqueueJobs(queueName, jobNames, jobBuilders); _driver.resume(queueName); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); } @Test public void testJobSubmitGenericWorkflows() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); Workflow.Builder builder = new Workflow.Builder(workflowName); for (int i = 0; i < 5; i++) { builder.addJob("JOB" + i, jobBuilder); } /** * Dependency visualization * JOB0 * * / | \ * * JOB1 <-JOB2 JOB4 * * | / * * JOB3 */ builder.addParentChildDependency("JOB0", "JOB1"); builder.addParentChildDependency("JOB0", "JOB2"); builder.addParentChildDependency("JOB0", "JOB4"); builder.addParentChildDependency("JOB1", "JOB2"); builder.addParentChildDependency("JOB2", "JOB3"); builder.addParentChildDependency("JOB4", "JOB3"); _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); } @Test public void testQueueParallelJobs() throws InterruptedException { final int parallelJobs = 3; final int numberOfJobsAddedBeforeControllerSwitch = 4; final int totalNumberOfJobs = 7; String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder() .setWorkflowId(queueName).setParallelJobs(parallelJobs).setAllowOverlapJobAssignment(true); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(Collections.singletonMap(MockTask.JOB_DELAY, "10000")); _driver.waitToStop(queueName, 5000L); // Add 4 jobs to the queue List<String> jobNames = new ArrayList<>(); List<JobConfig.Builder> jobBuilders = new ArrayList<>(); for (int i = 0; i < numberOfJobsAddedBeforeControllerSwitch; i++) { jobNames.add("JOB" + i); jobBuilders.add(jobBuilder); } _driver.enqueueJobs(queueName, jobNames, jobBuilders); _driver.resume(queueName); // Wait until all of the enqueued jobs (Job0 to Job3) are finished for (int i = 0; i < numberOfJobsAddedBeforeControllerSwitch; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + i), TaskState.COMPLETED); } // Stop the Controller _controller.syncStop(); // Add 3 more jobs to the queue which should run in parallel after the Controller is started jobNames.clear(); jobBuilders.clear(); for (int i = numberOfJobsAddedBeforeControllerSwitch; i < totalNumberOfJobs; i++) { jobNames.add("JOB" + i); jobBuilders.add(jobBuilder); } _driver.enqueueJobs(queueName, jobNames, jobBuilders); // Start the Controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // Wait until all of the newly added jobs (Job4 to Job6) are finished for (int i = numberOfJobsAddedBeforeControllerSwitch; i < totalNumberOfJobs; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + i), TaskState.COMPLETED); } // Make sure the jobs have been running in parallel by checking the jobs start time and finish // time long maxStartTime = Long.MIN_VALUE; long minFinishTime = Long.MAX_VALUE; for (int i = numberOfJobsAddedBeforeControllerSwitch; i < totalNumberOfJobs; i++) { JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(queueName, "JOB" + i)); maxStartTime = Long.max(maxStartTime, jobContext.getStartTime()); minFinishTime = Long.min(minFinishTime, jobContext.getFinishTime()); } Assert.assertTrue(minFinishTime > maxStartTime); } @Test public void testQueueJobsMaxCapacity() throws InterruptedException { final int numberOfJobsAddedInitially = 4; final int queueCapacity = 5; final String newJobName = "NewJob"; String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder().setWorkflowId(queueName).setParallelJobs(1) .setAllowOverlapJobAssignment(true).setCapacity(queueCapacity); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(Collections.singletonMap(MockTask.JOB_DELAY, "1000")); _driver.waitToStop(queueName, 5000L); // Add 4 jobs to the queue List<String> jobNames = new ArrayList<>(); List<JobConfig.Builder> jobBuilders = new ArrayList<>(); for (int i = 0; i < numberOfJobsAddedInitially; i++) { jobNames.add("JOB" + i); jobBuilders.add(jobBuilder); } _driver.enqueueJobs(queueName, jobNames, jobBuilders); _driver.resume(queueName); // Wait until all of the enqueued jobs (Job0 to Job3) are finished for (int i = 0; i < numberOfJobsAddedInitially; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + i), TaskState.COMPLETED); } boolean exceptionHappenedWhileAddingNewJob = false; try { // This call will produce the exception because 4 jobs have been already added // By adding the new job the queue will hit its capacity limit _driver.enqueueJob(queueName, newJobName, jobBuilder); } catch (Exception e) { exceptionHappenedWhileAddingNewJob = true; } Assert.assertTrue(exceptionHappenedWhileAddingNewJob); // Make sure that jobConfig has not been created JobConfig jobConfig = _driver.getJobConfig(TaskUtil.getNamespacedJobName(queueName, newJobName)); Assert.assertNull(jobConfig); } }
9,623
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestUnregisteredCommand.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestUnregisteredCommand extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); } @Test public void testUnregisteredCommand() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand("OtherCommand").setTimeoutPerTask(10000L).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); builder.addJob("JOB1", jobBuilder); _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")) .getPartitionState(0), TaskPartitionState.ERROR); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")) .getPartitionNumAttempts(0), 1); } }
9,624
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskRebalancer.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Map; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.AccessOption; import org.apache.helix.HelixDataAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobDag; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConstants; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.Test; public class TestTaskRebalancer extends TaskTestBase { @Test public void basic() throws Exception { basic(100); } @Test public void zeroTaskCompletionTime() throws Exception { basic(0); } @Test public void testExpiry() throws Exception { String jobName = "Expiry"; long expiry = 1000L; Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(100)); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(commandConfig); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName, jobBuilder) .setExpiry(expiry).build(); _driver.start(flow); _driver.pollForWorkflowState(jobName, TaskState.IN_PROGRESS); // Running workflow should have config and context viewable through accessor HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey workflowCfgKey = accessor.keyBuilder().resourceConfig(jobName); String workflowPropStoreKey = Joiner.on("/").join(TaskConstants.REBALANCER_CONTEXT_ROOT, jobName); // Ensure context and config exist Assert.assertTrue( _manager.getHelixPropertyStore().exists(workflowPropStoreKey, AccessOption.PERSISTENT)); Assert.assertNotSame(accessor.getProperty(workflowCfgKey), null); // Wait for job to finish and expire _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); long finishTime = _driver.getWorkflowContext(jobName).getFinishTime(); // Ensure workflow config and context were cleaned up by now Assert.assertTrue(TestHelper.verify( () -> (!_manager.getHelixPropertyStore().exists(workflowPropStoreKey, AccessOption.PERSISTENT) && accessor.getProperty(workflowCfgKey) == null), TestHelper.WAIT_DURATION)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - finishTime >= expiry); } private void basic(long jobCompletionTime) throws Exception { // We use a different resource name in each test method as a work around for a helix participant // bug where it does // not clear locally cached state when a resource partition is dropped. Once that is fixed we // should change these // tests to use the same resource name and implement a beforeMethod that deletes the task // resource. final String jobResource = "basic" + jobCompletionTime; Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(jobCompletionTime)); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(commandConfig); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait for job completion _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); // Ensure all partitions are completed individually JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(jobResource)); for (int i = 0; i < _numPartitions; i++) { Assert.assertEquals(ctx.getPartitionState(i), TaskPartitionState.COMPLETED); Assert.assertEquals(ctx.getPartitionNumAttempts(i), 1); } } @Test public void partitionSet() throws Exception { final String jobResource = "partitionSet"; ImmutableList<String> targetPartitions = ImmutableList.of("TestDB_1", "TestDB_2", "TestDB_3", "TestDB_5", "TestDB_8", "TestDB_13"); // construct and submit our basic workflow Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(100)); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(commandConfig).setMaxAttemptsPerTask(1) .setTargetPartitions(targetPartitions); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // wait for job completeness/timeout _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); // see if resulting context completed successfully for our partition set String namespacedName = TaskUtil.getNamespacedJobName(jobResource); JobContext ctx = _driver.getJobContext(namespacedName); WorkflowContext workflowContext = _driver.getWorkflowContext(jobResource); Assert.assertNotNull(ctx); Assert.assertNotNull(workflowContext); Assert.assertEquals(workflowContext.getJobState(namespacedName), TaskState.COMPLETED); for (String pName : targetPartitions) { int i = ctx.getPartitionsByTarget().get(pName).get(0); Assert.assertEquals(ctx.getPartitionState(i), TaskPartitionState.COMPLETED); Assert.assertEquals(ctx.getPartitionNumAttempts(i), 1); } } @Test public void testRepeatedWorkflow() throws Exception { String workflowName = "SomeWorkflow"; Workflow flow = WorkflowGenerator.generateDefaultRepeatedJobWorkflowBuilder(workflowName).build(); new TaskDriver(_manager).start(flow); // Wait until the workflow completes _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); // Assert completion for all tasks within two minutes for (String task : flow.getJobConfigs().keySet()) { _driver.pollForJobState(workflowName, task, TaskState.COMPLETED); } } @Test public void timeouts() throws Exception { final String jobResource = "timeouts"; JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG) .setMaxAttemptsPerTask(2).setTimeoutPerTask(1); // This timeout needs to be very short Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait until the job reports failure. _driver.pollForWorkflowState(jobResource, TaskState.FAILED); // Check that all partitions timed out up to maxAttempts JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(jobResource)); int maxAttempts = 0; boolean sawTimedoutTask = false; for (int i = 0; i < _numPartitions; i++) { TaskPartitionState state = ctx.getPartitionState(i); if (state != null) { if (state == TaskPartitionState.TIMED_OUT) { sawTimedoutTask = true; } // At least one task timed out, other might be aborted due to job failure. Assert.assertTrue( state == TaskPartitionState.TIMED_OUT || state == TaskPartitionState.TASK_ABORTED); maxAttempts = Math.max(maxAttempts, ctx.getPartitionNumAttempts(i)); } } Assert.assertTrue(sawTimedoutTask); // 2 or 3 both okay only for tests - TODO: Fix this later Assert.assertTrue(maxAttempts == 2 || maxAttempts == 3); } @Test public void testNamedQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue JobQueue queue = new JobQueue.Builder(queueName).build(); _driver.createQueue(queue); // Enqueue jobs Set<String> master = Sets.newHashSet("MASTER"); Set<String> slave = Sets.newHashSet("SLAVE"); JobConfig.Builder job1 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB).setTargetPartitionStates(master); JobConfig.Builder job2 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB).setTargetPartitionStates(slave); _driver.enqueueJob(queueName, "masterJob", job1); _driver.enqueueJob(queueName, "slaveJob", job2); // Ensure successful completion String namespacedJob1 = queueName + "_masterJob"; String namespacedJob2 = queueName + "_slaveJob"; _driver.pollForJobState(queueName, namespacedJob1, TaskState.COMPLETED); _driver.pollForJobState(queueName, namespacedJob2, TaskState.COMPLETED); JobContext masterJobContext = _driver.getJobContext(namespacedJob1); JobContext slaveJobContext = _driver.getJobContext(namespacedJob2); // Ensure correct ordering long job1Finish = masterJobContext.getFinishTime(); long job2Start = slaveJobContext.getStartTime(); Assert.assertTrue(job2Start >= job1Finish); // Flush queue and check cleanup _driver.flushQueue(queueName); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Assert.assertNull(accessor.getProperty(keyBuilder.idealStates(namespacedJob1))); Assert.assertNull(accessor.getProperty(keyBuilder.resourceConfig(namespacedJob1))); Assert.assertNull(accessor.getProperty(keyBuilder.idealStates(namespacedJob2))); Assert.assertNull(accessor.getProperty(keyBuilder.resourceConfig(namespacedJob2))); WorkflowConfig workflowCfg = _driver.getWorkflowConfig(queueName); JobDag dag = workflowCfg.getJobDag(); Assert.assertFalse(dag.getAllNodes().contains(namespacedJob1)); Assert.assertFalse(dag.getAllNodes().contains(namespacedJob2)); Assert.assertFalse(dag.getChildrenToParents().containsKey(namespacedJob1)); Assert.assertFalse(dag.getChildrenToParents().containsKey(namespacedJob2)); Assert.assertFalse(dag.getParentsToChildren().containsKey(namespacedJob1)); Assert.assertFalse(dag.getParentsToChildren().containsKey(namespacedJob2)); } }
9,625
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobAndWorkflowType.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.Map; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; public class TestJobAndWorkflowType extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestJobAndWorkflowType.class); private static final String DEFAULT_TYPE = "DEFAULT"; @Test public void testJobAndWorkflowType() throws InterruptedException { LOG.info("Start testing job and workflow type"); String jobName = TestHelper.getTestMethodName(); JobConfig.Builder jobConfig = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG).setJobType(DEFAULT_TYPE); Map<String, String> tmp = new HashMap<>(); tmp.put("WorkflowType", DEFAULT_TYPE); Workflow.Builder builder = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName, jobConfig).fromMap(tmp); // Start workflow _driver.start(builder.build()); _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); String fetchedJobType = _driver.getJobConfig(String.format("%s_%s", jobName, jobName)).getJobType(); String fetchedWorkflowType = _driver.getWorkflowConfig(jobName).getWorkflowType(); Assert.assertEquals(fetchedJobType, DEFAULT_TYPE); Assert.assertEquals(fetchedWorkflowType, DEFAULT_TYPE); } }
9,626
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TaskTestUtil.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.util.RebalanceUtil; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.common.DedupEventProcessor; import org.apache.helix.controller.dataproviders.WorkflowControllerDataProvider; import org.apache.helix.controller.pipeline.AsyncWorkerType; import org.apache.helix.controller.pipeline.Stage; import org.apache.helix.controller.pipeline.StageContext; import org.apache.helix.controller.stages.AttributeName; import org.apache.helix.controller.stages.BestPossibleStateOutput; import org.apache.helix.controller.stages.ClusterEvent; import org.apache.helix.controller.stages.ClusterEventType; import org.apache.helix.controller.stages.CurrentStateComputationStage; import org.apache.helix.controller.stages.ReadClusterDataStage; import org.apache.helix.controller.stages.ResourceComputationStage; import org.apache.helix.controller.stages.TaskGarbageCollectionStage; import org.apache.helix.controller.stages.task.TaskPersistDataStage; import org.apache.helix.controller.stages.task.TaskSchedulingStage; import org.apache.helix.model.Message; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobQueue; import org.apache.helix.task.ScheduleConfig; import org.apache.helix.task.TargetState; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; /** * Static test utility methods. */ public class TaskTestUtil { public static final String JOB_KW = "JOB"; private final static int _default_timeout = 2 * 60 * 1000; /* 2 mins */ public static void pollForEmptyJobState(final TaskDriver driver, final String workflowName, final String jobName) throws Exception { final String namespacedJobName = String.format("%s_%s", workflowName, jobName); boolean succeed = TestHelper.verify(new TestHelper.Verifier() { @Override public boolean verify() throws Exception { WorkflowContext ctx = driver.getWorkflowContext(workflowName); return ctx == null || ctx.getJobState(namespacedJobName) == null || ctx.getJobState(namespacedJobName) == TaskState.NOT_STARTED; } }, _default_timeout); Assert.assertTrue(succeed); } public static WorkflowContext pollForWorkflowContext(TaskDriver driver, String workflowResource) throws InterruptedException { // Wait for completion. long st = System.currentTimeMillis(); WorkflowContext ctx; do { ctx = driver.getWorkflowContext(workflowResource); Thread.sleep(100); } while (ctx == null && System.currentTimeMillis() < st + _default_timeout); Assert.assertNotNull(ctx); return ctx; } // 1. Different jobs in a same work flow is in RUNNING at the same time // 2. When disallow overlap assignment, no two jobs in the same work flow is in RUNNING at the same instance // Use this method with caution because it assumes workflow doesn't finish too quickly and number of parallel running // tasks can be counted. public static boolean pollForWorkflowParallelState(TaskDriver driver, String workflowName) throws InterruptedException { WorkflowConfig workflowConfig = driver.getWorkflowConfig(workflowName); Assert.assertNotNull(workflowConfig); WorkflowContext workflowContext = null; while (workflowContext == null) { workflowContext = driver.getWorkflowContext(workflowName); Thread.sleep(100); } int maxRunningCount = 0; boolean finished = false; while (!finished) { finished = true; int runningCount = 0; workflowContext = driver.getWorkflowContext(workflowName); for (String jobName : workflowConfig.getJobDag().getAllNodes()) { TaskState jobState = workflowContext.getJobState(jobName); if (jobState == TaskState.IN_PROGRESS) { ++runningCount; finished = false; } } if (runningCount > maxRunningCount ) { maxRunningCount = runningCount; } Thread.sleep(100); } List<JobContext> jobContextList = new ArrayList<>(); for (String jobName : workflowConfig.getJobDag().getAllNodes()) { JobContext jobContext = driver.getJobContext(jobName); if (jobContext != null) { jobContextList.add(driver.getJobContext(jobName)); } } Map<String, List<long[]>> rangeMap = new HashMap<>(); if (!workflowConfig.isAllowOverlapJobAssignment()) { for (JobContext jobContext : jobContextList) { for (int partition : jobContext.getPartitionSet()) { String instance = jobContext.getAssignedParticipant(partition); if (!rangeMap.containsKey(instance)) { rangeMap.put(instance, new ArrayList<long[]>()); } rangeMap.get(instance).add(new long[] { jobContext.getPartitionStartTime(partition), jobContext.getPartitionFinishTime(partition) }); } } } for (List<long[]> timeRange : rangeMap.values()) { Collections.sort(timeRange, new Comparator<long[]>() { @Override public int compare(long[] o1, long[] o2) { return (int) (o1[0] - o2[0]); } }); for (int i = 0; i < timeRange.size() - 1; i++) { if (timeRange.get(i)[1] > timeRange.get(i + 1)[0]) { return false; } } } return maxRunningCount > 1 && (workflowConfig.isJobQueue() ? maxRunningCount <= workflowConfig .getParallelJobs() : true); } public static Date getDateFromStartTime(String startTime) { int splitIndex = startTime.indexOf(':'); int hourOfDay = 0, minutes = 0; try { hourOfDay = Integer.parseInt(startTime.substring(0, splitIndex)); minutes = Integer.parseInt(startTime.substring(splitIndex + 1)); } catch (NumberFormatException e) { } Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, hourOfDay); cal.set(Calendar.MINUTE, minutes); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } public static JobQueue.Builder buildRecurrentJobQueue(String jobQueueName, int delayStart) { return buildRecurrentJobQueue(jobQueueName, delayStart, 60); } public static JobQueue.Builder buildRecurrentJobQueue(String jobQueueName, int delayStart, int recurrenceInSeconds) { return buildRecurrentJobQueue(jobQueueName, delayStart, recurrenceInSeconds, null); } public static JobQueue.Builder buildRecurrentJobQueue(String jobQueueName, int delayStart, int recurrenceInSeconds, TargetState targetState) { WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder(jobQueueName); workflowCfgBuilder.setExpiry(120000); if (targetState != null) { workflowCfgBuilder.setTargetState(TargetState.STOP); } Calendar cal = Calendar.getInstance(); cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + delayStart / 60); cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + delayStart % 60); cal.set(Calendar.MILLISECOND, 0); ScheduleConfig scheduleConfig = ScheduleConfig.recurringFromDate(cal.getTime(), TimeUnit.SECONDS, recurrenceInSeconds); workflowCfgBuilder.setScheduleConfig(scheduleConfig); return new JobQueue.Builder(jobQueueName).setWorkflowConfig(workflowCfgBuilder.build()); } public static JobQueue.Builder buildRecurrentJobQueue(String jobQueueName) { return buildRecurrentJobQueue(jobQueueName, 0); } public static JobQueue.Builder buildJobQueue(String jobQueueName, int delayStart, int failureThreshold, int capacity) { WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder(jobQueueName); workflowCfgBuilder.setExpiry(120000); workflowCfgBuilder.setCapacity(capacity); Calendar cal = Calendar.getInstance(); cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + delayStart / 60); cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + delayStart % 60); cal.set(Calendar.MILLISECOND, 0); workflowCfgBuilder.setScheduleConfig(ScheduleConfig.oneTimeDelayedStart(cal.getTime())); if (failureThreshold > 0) { workflowCfgBuilder.setFailureThreshold(failureThreshold); } return new JobQueue.Builder(jobQueueName).setWorkflowConfig(workflowCfgBuilder.build()); } public static JobQueue.Builder buildJobQueue(String jobQueueName, int delayStart, int failureThreshold) { return buildJobQueue(jobQueueName, delayStart, failureThreshold, 500); } public static JobQueue.Builder buildJobQueue(String jobQueueName) { return buildJobQueue(jobQueueName, 0, 0, 500); } public static JobQueue.Builder buildJobQueue(String jobQueueName, int capacity) { return buildJobQueue(jobQueueName, 0, 0, capacity); } public static WorkflowContext buildWorkflowContext(String workflowResource, TaskState workflowState, Long startTime, TaskState... jobStates) { WorkflowContext workflowContext = new WorkflowContext(new ZNRecord(TaskUtil.WORKFLOW_CONTEXT_KW)); workflowContext.setName(workflowResource); workflowContext.setStartTime(startTime == null ? System.currentTimeMillis() : startTime); int jobId = 0; for (TaskState jobstate : jobStates) { workflowContext .setJobState(TaskUtil.getNamespacedJobName(workflowResource, JOB_KW) + jobId++, jobstate); } workflowContext.setWorkflowState(workflowState); return workflowContext; } public static JobContext buildJobContext(Long startTime, Long finishTime, TaskPartitionState... partitionStates) { JobContext jobContext = new JobContext(new ZNRecord(TaskUtil.TASK_CONTEXT_KW)); jobContext.setStartTime(startTime == null ? System.currentTimeMillis() : startTime); jobContext.setFinishTime(finishTime == null ? System.currentTimeMillis() : finishTime); int partitionId = 0; for (TaskPartitionState partitionState : partitionStates) { jobContext.setPartitionState(partitionId++, partitionState); } return jobContext; } public static WorkflowControllerDataProvider buildDataProvider(HelixDataAccessor accessor, String clusterName) { WorkflowControllerDataProvider cache = new WorkflowControllerDataProvider(clusterName); cache.refresh(accessor); return cache; } public static BestPossibleStateOutput calculateTaskSchedulingStage(WorkflowControllerDataProvider cache, HelixManager manager) throws Exception { ClusterEvent event = new ClusterEvent(ClusterEventType.Unknown); event.addAttribute(AttributeName.ControllerDataProvider.name(), cache); event.addAttribute(AttributeName.helixmanager.name(), manager); event.addAttribute(AttributeName.PipelineType.name(), "TASK"); Map<AsyncWorkerType, DedupEventProcessor<String, Runnable>> asyncFIFOWorkerPool = new HashMap<>(); DedupEventProcessor<String, Runnable> worker = new DedupEventProcessor<String, Runnable>("ClusterName", AsyncWorkerType.TaskJobPurgeWorker.name()) { @Override protected void handleEvent(Runnable event) { // TODO: retry when queue is empty and event.run() failed? event.run(); } }; worker.start(); asyncFIFOWorkerPool.put(AsyncWorkerType.TaskJobPurgeWorker, worker); event.addAttribute(AttributeName.AsyncFIFOWorkerPool.name(), asyncFIFOWorkerPool); List<Stage> stages = new ArrayList<Stage>(); stages.add(new ReadClusterDataStage()); stages.add(new ResourceComputationStage()); stages.add(new CurrentStateComputationStage()); stages.add(new TaskSchedulingStage()); stages.add(new TaskPersistDataStage()); stages.add(new TaskGarbageCollectionStage()); for (Stage stage : stages) { RebalanceUtil.runStage(event, stage); } return event.getAttribute(AttributeName.BEST_POSSIBLE_STATE.name()); } public static boolean pollForAllTasksBlock(HelixDataAccessor accessor, String instance, int numTask, long timeout) throws InterruptedException { PropertyKey propertyKey = accessor.keyBuilder().messages(instance); long startTime = System.currentTimeMillis(); while (true) { List<Message> messages = accessor.getChildValues(propertyKey, true); if (allTasksBlock(messages, numTask)) { return true; } else if (startTime + timeout < System.currentTimeMillis()) { return false; } else { Thread.sleep(100); } } } private static boolean allTasksBlock(List<Message> messages, int numTask) { if (messages.size() != numTask) { return false; } for (Message message : messages) { if (!message.getFromState().equals(TaskPartitionState.INIT.name()) || !message.getToState().equals(TaskPartitionState.RUNNING.name())) { return false; } } return true; } /** * Implement this class to periodically check whether a defined condition is true, * if timeout, check the condition for the last time and return the result. */ public static abstract class Poller { private static final long DEFAULT_TIME_OUT = 1000*10; public boolean poll() { return poll(DEFAULT_TIME_OUT); } public boolean poll(long timeOut) { long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < startTime + timeOut) { if (check()) { break; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new IllegalStateException(e); } } return check(); } public abstract boolean check(); } }
9,627
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailureTaskNotStarted.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixException; import org.apache.helix.TestHelper; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.mock.statemodel.MockTaskStateModelFactory; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.IdealState; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.Task; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskSynchronizedTestBase; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestJobFailureTaskNotStarted extends TaskSynchronizedTestBase { private static final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB; private static final String UNBALANCED_DB_NAME = "UnbalancedDB"; private MockParticipantManager _blockedParticipant; private MockParticipantManager _normalParticipant; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; _numDbs = 1; _numNodes = 2; _numPartitions = 2; _numReplicas = 1; _gSetupTool.addCluster(CLUSTER_NAME, true); setupParticipants(); setupDBs(); startParticipantsWithStuckTaskStateModelFactory(); createManagers(); _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); // Enable cancellation ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient); ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME); clusterConfig.stateTransitionCancelEnabled(true); _configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME) .setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); } protected void startParticipantsWithStuckTaskStateModelFactory() { Map<String, TaskFactory> taskFactoryReg = new HashMap<String, TaskFactory>(); taskFactoryReg.put(MockTask.TASK_COMMAND, new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new MockTask(context); } }); List<String> instances = _gSetupTool.getClusterManagementTool().getInstancesInCluster(CLUSTER_NAME); _participants[0] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instances.get(0)); StateMachineEngine stateMachine = _participants[0].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new MockTaskStateModelFactory(_participants[0], taskFactoryReg)); _participants[0].syncStart(); _blockedParticipant = _participants[0]; _participants[1] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instances.get(1)); stateMachine = _participants[1].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[1], taskFactoryReg)); _participants[1].syncStart(); _normalParticipant = _participants[1]; } @Test public void testTaskNotStarted() throws InterruptedException { setupUnbalancedDB(); final String BLOCK_WORKFLOW_NAME = "blockWorkflow"; final String FAIL_WORKFLOW_NAME = "failWorkflow"; final String FAIL_JOB_NAME = "failJob"; ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient); final int numTask = configAccessor.getClusterConfig(CLUSTER_NAME).getMaxConcurrentTaskPerInstance(); // Tasks targeting the unbalanced DB, the instance is setup to stuck on INIT->RUNNING, so it // takes all threads // on that instance. JobConfig.Builder blockJobBuilder = new JobConfig.Builder().setWorkflow(BLOCK_WORKFLOW_NAME) .setTargetResource(UNBALANCED_DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setNumConcurrentTasksPerInstance(numTask); Workflow.Builder blockWorkflowBuilder = new Workflow.Builder(BLOCK_WORKFLOW_NAME).addJob("blockJob", blockJobBuilder); _driver.start(blockWorkflowBuilder.build()); Assert.assertTrue(TaskTestUtil.pollForAllTasksBlock(_manager.getHelixDataAccessor(), _blockedParticipant.getInstanceName(), numTask, 10000)); // Now, all HelixTask threads are stuck at INIT->RUNNING for task state transition(user task // can't be submitted) // New tasks assigned to the instance won't start INIT->RUNNING transition at all. // A to-be-failed job, 2 tasks, 1 stuck and 1 fail, making the job fail. JobConfig.Builder failJobBuilder = new JobConfig.Builder().setWorkflow(FAIL_WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setJobCommandConfigMap( ImmutableMap.of(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FAILED.name())); Workflow.Builder failWorkflowBuilder = new Workflow.Builder(FAIL_WORKFLOW_NAME).addJob(FAIL_JOB_NAME, failJobBuilder); _driver.start(failWorkflowBuilder.build()); _driver.pollForJobState(FAIL_WORKFLOW_NAME, TaskUtil.getNamespacedJobName(FAIL_WORKFLOW_NAME, FAIL_JOB_NAME), TaskState.FAILED); _driver.pollForWorkflowState(FAIL_WORKFLOW_NAME, TaskState.FAILED); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(FAIL_WORKFLOW_NAME, FAIL_JOB_NAME)); for (int pId : jobContext.getPartitionSet()) { String assignedParticipant = jobContext.getAssignedParticipant(pId); if (assignedParticipant == null) { continue; // May not have been assigned at all due to quota limitations } if (jobContext.getAssignedParticipant(pId).equals(_blockedParticipant.getInstanceName())) { Assert.assertEquals(jobContext.getPartitionState(pId), TaskPartitionState.TASK_ABORTED); } else if (assignedParticipant.equals(_normalParticipant.getInstanceName())) { Assert.assertEquals(jobContext.getPartitionState(pId), TaskPartitionState.TASK_ERROR); } else { throw new HelixException("There should be only 2 instances, 1 blocked, 1 normal."); } } } private void setupUnbalancedDB() throws InterruptedException { // Start with Full-Auto mode to create the partitions, Semi-Auto won't create partitions. _gSetupTool.addResourceToCluster(CLUSTER_NAME, UNBALANCED_DB_NAME, 50, MASTER_SLAVE_STATE_MODEL, IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, UNBALANCED_DB_NAME, 1); // Set preference list to put all partitions to one instance. IdealState idealState = _gSetupTool.getClusterManagementTool() .getResourceIdealState(CLUSTER_NAME, UNBALANCED_DB_NAME); Set<String> partitions = idealState.getPartitionSet(); for (String partition : partitions) { idealState.setPreferenceList(partition, Lists.newArrayList(_blockedParticipant.getInstanceName())); } idealState.setRebalanceMode(IdealState.RebalanceMode.SEMI_AUTO); _gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, UNBALANCED_DB_NAME, idealState); Assert.assertTrue(_clusterVerifier.verifyByPolling(10000, 100)); } }
9,628
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestWorkflowTermination.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.monitoring.mbeans.MonitorDomainNames; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This test contains cases when a workflow finish */ public class TestWorkflowTermination extends TaskTestBase { private final static String JOB_NAME = "TestJob"; private final static String WORKFLOW_TYPE = "DEFAULT"; private static final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); @BeforeClass public void beforeClass() throws Exception { _numDbs = 1; _numNodes = 3; _numPartitions = 5; _numReplicas = 3; super.beforeClass(); } private JobConfig.Builder createJobConfigBuilder(String workflow, boolean shouldJobFail, long timeoutMs) { String taskState = shouldJobFail ? TaskState.FAILED.name() : TaskState.COMPLETED.name(); return new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setWorkflow(workflow).setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(5) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, Long.toString(timeoutMs), MockTask.TASK_RESULT_STATUS, taskState)); } @Test public void testWorkflowSucceed() throws Exception { String workflowName = TestHelper.getTestMethodName(); long workflowExpiry = 2000; long timeout = 2000; JobConfig.Builder jobBuilder = createJobConfigBuilder(workflowName, false, 50); jobBuilder.setWorkflow(workflowName); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName) .setWorkflowConfig(new WorkflowConfig.Builder(workflowName).setTimeout(timeout) .setWorkFlowType(WORKFLOW_TYPE).build()) .addJob(JOB_NAME, jobBuilder).setExpiry(workflowExpiry); _driver.start(workflowBuilder.build()); // Timeout is longer than job finish so workflow status should be COMPLETED _driver.pollForWorkflowState(workflowName, 5000L, TaskState.COMPLETED); long finishTime = _driver.getWorkflowContext(workflowName).getFinishTime(); WorkflowContext context = _driver.getWorkflowContext(workflowName); Assert.assertTrue(context.getFinishTime() - context.getStartTime() < timeout); // Workflow should be cleaned up after expiry verifyWorkflowCleanup(workflowName, getJobNameToPoll(workflowName, JOB_NAME)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - finishTime >= workflowExpiry); ObjectName objectName = getWorkflowMBeanObjectName(workflowName); Assert.assertEquals((long) beanServer.getAttribute(objectName, "SuccessfulWorkflowCount"), 1); Assert .assertTrue((long) beanServer.getAttribute(objectName, "MaximumWorkflowLatencyGauge") > 0); Assert.assertTrue((long) beanServer.getAttribute(objectName, "TotalWorkflowLatencyCount") > 0); } @Test public void testWorkflowRunningTimeout() throws Exception { String workflowName = TestHelper.getTestMethodName(); String notStartedJobName = JOB_NAME + "-NotStarted"; long workflowExpiry = 2000; // 2sec expiry time long timeout = 50; JobConfig.Builder jobBuilder = createJobConfigBuilder(workflowName, false, 5000); jobBuilder.setWorkflow(workflowName); // Create a workflow where job2 depends on job1. Workflow would timeout before job1 finishes Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName) .setWorkflowConfig(new WorkflowConfig.Builder(workflowName).setTimeout(timeout) .setWorkFlowType(WORKFLOW_TYPE).build()) .addJob(JOB_NAME, jobBuilder).addJob(notStartedJobName, jobBuilder) .addParentChildDependency(JOB_NAME, notStartedJobName).setExpiry(workflowExpiry); _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, 10000L, TaskState.TIMED_OUT); long finishTime = _driver.getWorkflowContext(workflowName).getFinishTime(); // Running job should be marked as timeout // and job not started should not appear in workflow context _driver.pollForJobState(workflowName, getJobNameToPoll(workflowName, JOB_NAME), 10000L, TaskState.TIMED_OUT); WorkflowContext context = _driver.getWorkflowContext(workflowName); Assert.assertNull(context.getJobState(notStartedJobName)); Assert.assertTrue(context.getFinishTime() - context.getStartTime() >= timeout); verifyWorkflowCleanup(workflowName, getJobNameToPoll(workflowName, JOB_NAME), getJobNameToPoll(workflowName, notStartedJobName)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - finishTime >= workflowExpiry); } @Test public void testWorkflowPausedTimeout() throws Exception { String workflowName = TestHelper.getTestMethodName(); long workflowExpiry = 2000; // 2sec expiry time long timeout = 5000; String notStartedJobName = JOB_NAME + "-NotStarted"; JobConfig.Builder jobBuilder = createJobConfigBuilder(workflowName, false, 5000); jobBuilder.setWorkflow(workflowName); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName) .setWorkflowConfig(new WorkflowConfig.Builder(workflowName).setTimeout(timeout) .setWorkFlowType(WORKFLOW_TYPE).build()) .addJob(JOB_NAME, jobBuilder).addJob(notStartedJobName, jobBuilder) .addParentChildDependency(JOB_NAME, notStartedJobName).setExpiry(workflowExpiry); _driver.start(workflowBuilder.build()); // Wait a bit for the job to get scheduled. Job runs for 100ms so this will very likely // to trigger a job stopped Thread.sleep(100); // Pause the queue _driver.waitToStop(workflowName, 20000L); _driver.pollForJobState(workflowName, getJobNameToPoll(workflowName, JOB_NAME), 10000L, TaskState.STOPPED); WorkflowContext context = _driver.getWorkflowContext(workflowName); Assert.assertNull(context.getJobState(notStartedJobName)); _driver.pollForWorkflowState(workflowName, 10000L, TaskState.TIMED_OUT); long finishTime = _driver.getWorkflowContext(workflowName).getFinishTime(); context = _driver.getWorkflowContext(workflowName); Assert.assertTrue(context.getFinishTime() - context.getStartTime() >= timeout); verifyWorkflowCleanup(workflowName, getJobNameToPoll(workflowName, JOB_NAME), getJobNameToPoll(workflowName, notStartedJobName)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - finishTime >= workflowExpiry); } @Test public void testJobQueueNotApplyTimeout() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); long timeout = 1000; // Make jobs run success JobConfig.Builder jobBuilder = createJobConfigBuilder(queueName, false, 10); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(queueName); jobQueue .setWorkflowConfig(new WorkflowConfig.Builder(queueName).setTimeout(timeout) .setWorkFlowType(WORKFLOW_TYPE).build()) .enqueueJob(JOB_NAME, jobBuilder).enqueueJob(JOB_NAME + 1, jobBuilder); _driver.start(jobQueue.build()); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, JOB_NAME), TaskState.COMPLETED); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, JOB_NAME + 1), TaskState.COMPLETED); Thread.sleep(timeout); // Verify that job queue is still in progress _driver.pollForWorkflowState(queueName, 10000L, TaskState.IN_PROGRESS); } @Test public void testWorkflowJobFail() throws Exception { String workflowName = TestHelper.getTestMethodName(); String job1 = JOB_NAME + "1"; String job2 = JOB_NAME + "2"; String job3 = JOB_NAME + "3"; String job4 = JOB_NAME + "4"; long workflowExpiry = 10000; long timeout = 10000; JobConfig.Builder jobBuilder = createJobConfigBuilder(workflowName, false, 1); JobConfig.Builder failedJobBuilder = createJobConfigBuilder(workflowName, true, 1); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName) .setWorkflowConfig(new WorkflowConfig.Builder(workflowName).setWorkFlowType(WORKFLOW_TYPE) .setTimeout(timeout).setParallelJobs(4).setFailureThreshold(1).build()) .addJob(job1, jobBuilder).addJob(job2, jobBuilder).addJob(job3, failedJobBuilder) .addJob(job4, jobBuilder).addParentChildDependency(job1, job2) .addParentChildDependency(job1, job3).addParentChildDependency(job2, job4) .addParentChildDependency(job3, job4).setExpiry(workflowExpiry); _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, 10000L, TaskState.FAILED); // Timeout is longer than fail time, so the failover should occur earlier WorkflowContext context = _driver.getWorkflowContext(workflowName); long finishTime = context.getFinishTime(); Assert.assertTrue(context.getFinishTime() - context.getStartTime() < timeout); // job1 will complete _driver.pollForJobState(workflowName, getJobNameToPoll(workflowName, job1), 10000L, TaskState.COMPLETED); // Possible race between 2 and 3 so it's likely for job2 to stay in either COMPLETED or ABORTED _driver.pollForJobState(workflowName, getJobNameToPoll(workflowName, job2), 10000L, TaskState.COMPLETED, TaskState.ABORTED); // job3 meant to fail _driver.pollForJobState(workflowName, getJobNameToPoll(workflowName, job3), 10000L, TaskState.FAILED); // because job4 has dependency over job3, it will fail as well _driver.pollForJobState(workflowName, getJobNameToPoll(workflowName, job4), 10000L, TaskState.FAILED); // Check MBean is updated ObjectName objectName = getWorkflowMBeanObjectName(workflowName); Assert.assertEquals((long) beanServer.getAttribute(objectName, "FailedWorkflowCount"), 1); // For a failed workflow, after timing out, it will be purged verifyWorkflowCleanup(workflowName, getJobNameToPoll(workflowName, job1), getJobNameToPoll(workflowName, job2), getJobNameToPoll(workflowName, job3), getJobNameToPoll(workflowName, job4)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - finishTime >= workflowExpiry); } private void verifyWorkflowCleanup(String workflowName, String... jobNames) throws Exception { // Verify workflow config and workflow context have been deleted Assert .assertTrue( TestHelper.verify( () -> (_driver.getWorkflowConfig(workflowName) == null && _driver.getWorkflowContext(workflowName) == null), TestHelper.WAIT_DURATION)); // Verify job config and job context have been deleted for (String job : jobNames) { Assert.assertTrue(TestHelper.verify( () -> (_driver.getJobConfig(job) == null && _driver.getJobContext(job) == null), TestHelper.WAIT_DURATION)); } } private static String getJobNameToPoll(String workflowName, String jobName) { return String.format("%s_%s", workflowName, jobName); } private ObjectName getWorkflowMBeanObjectName(String workflowName) throws MalformedObjectNameException { return new ObjectName(String.format("%s:%s=%s, %s=%s", MonitorDomainNames.ClusterStatus.name(), "cluster", CLUSTER_NAME, "workflowType", WORKFLOW_TYPE)); } }
9,629
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TaskTestBase.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.task.TaskSynchronizedTestBase; import org.testng.Assert; import org.testng.annotations.BeforeClass; public class TaskTestBase extends TaskSynchronizedTestBase { @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); // start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); } }
9,630
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestStopAndResumeQueue.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test to check if context of the queue gets properly updated even when there is no job queued in * it. */ public class TestStopAndResumeQueue extends TaskTestBase { private static final String DATABASE = WorkflowGenerator.DEFAULT_TGT_DB; @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; _numNodes = 3; super.beforeClass(); } @Test public void testStopAndResumeQueue() throws Exception { String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder0 = new JobConfig.Builder().setWorkflow(jobQueueName).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("JOB0", jobBuilder0); _driver.start(jobQueue.build()); _driver.pollForWorkflowState(jobQueueName, TaskState.IN_PROGRESS); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"), TaskState.COMPLETED); _driver.waitToStop(jobQueueName, 50000L); _driver.resume(jobQueueName); // Resume should change the workflow context's state to IN_PROGRESS even when there is no job // running _driver.pollForWorkflowState(jobQueueName, TaskState.IN_PROGRESS); } }
9,631
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestFailTargetJobWhenResourceDisabled.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestFailTargetJobWhenResourceDisabled extends TaskTestBase { private JobConfig.Builder _jobCfg; private String _jobName; @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); _jobName = "TestJob"; _jobCfg = new JobConfig.Builder().setJobId(_jobName).setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB); } @Test public void testJobScheduleAfterResourceDisabled() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); _gSetupTool.getClusterManagementTool() .enableResource(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, false); Workflow.Builder workflow = new Workflow.Builder(workflowName); workflow.addJob(_jobName, _jobCfg); _driver.start(workflow.build()); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); } @Test public void testJobScheduleBeforeResourceDisabled() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflow = new Workflow.Builder(workflowName); _jobCfg.setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000000")); workflow.addJob(_jobName, _jobCfg); _driver.start(workflow.build()); Thread.sleep(1000); _gSetupTool.getClusterManagementTool() .enableResource(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, false); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); } }
9,632
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskErrorReporting.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.Test; /** * Test Error reporting for failed tasks */ public class TestTaskErrorReporting extends TaskTestBase { @Test public void test() throws Exception { int taskRetryCount = 1; int num_tasks = 5; String jobResource = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder(); jobBuilder.setCommand(MockTask.TASK_COMMAND).setTimeoutPerTask(10000) .setMaxAttemptsPerTask(taskRetryCount).setFailureThreshold(Integer.MAX_VALUE); // create each task configs. final int abortedTask = 1; final int failedTask = 2; final int exceptionTask = 3; final String abortedMsg = "This task aborted, some terrible things must happened."; final String failedMsg = "This task failed, something may be wrong."; final String exceptionMsg = "This task throws exception."; final String successMsg = "Yes, we did it!"; List<TaskConfig> taskConfigs = new ArrayList<TaskConfig>(); for (int j = 0; j < num_tasks; j++) { TaskConfig.Builder configBuilder = new TaskConfig.Builder().setTaskId("task_" + j); switch (j) { case abortedTask: configBuilder.addConfig(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FATAL_FAILED.name()) .addConfig(MockTask.ERROR_MESSAGE, abortedMsg); break; case failedTask: configBuilder.addConfig(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FAILED.name()) .addConfig(MockTask.ERROR_MESSAGE, failedMsg); break; case exceptionTask: configBuilder.addConfig(MockTask.THROW_EXCEPTION, Boolean.TRUE.toString()) .addConfig(MockTask.ERROR_MESSAGE, exceptionMsg); break; default: configBuilder.addConfig(MockTask.ERROR_MESSAGE, successMsg); break; } configBuilder.setTargetPartition(String.valueOf(j)); taskConfigs.add(configBuilder.build()); } jobBuilder.addTaskConfigs(taskConfigs); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait until the job completes. _driver.pollForWorkflowState(jobResource, TaskState.COMPLETED); JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(jobResource)); for (int i = 0; i < num_tasks; i++) { TaskPartitionState state = ctx.getPartitionState(i); String taskId = ctx.getTaskIdForPartition(i); String errMsg = ctx.getPartitionInfo(i); if (taskId.equals("task_" + abortedTask)) { Assert.assertEquals(state, TaskPartitionState.TASK_ABORTED); Assert.assertEquals(errMsg, abortedMsg); } else if (taskId.equals("task_" + failedTask)) { Assert.assertEquals(state, TaskPartitionState.TASK_ERROR); Assert.assertEquals(errMsg, failedMsg); } else if (taskId.equals("task_" + exceptionTask)) { Assert.assertEquals(state, TaskPartitionState.TASK_ERROR); Assert.assertTrue(errMsg.contains(exceptionMsg)); } else { Assert.assertEquals(state, TaskPartitionState.COMPLETED); Assert.assertEquals(errMsg, successMsg); } } } }
9,633
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestDropCurrentStateRunningTask.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.Map; import org.apache.helix.AccessOption; import org.apache.helix.TestHelper; import org.apache.helix.ZkTestHelper; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.CurrentState; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; public class TestDropCurrentStateRunningTask extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _numNodes = 3; _numPartitions = 1; super.beforeClass(); // Stop participants that have been started in super class for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } _participants = new MockParticipantManager[_numNodes]; startParticipant(2); } @AfterClass public void afterClass() throws Exception { super.afterClass(); } @Test public void testDropCurrentStateRunningTask() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName), TaskState.IN_PROGRESS); String namespacedJobName = TaskUtil.getNamespacedJobName(workflowName, jobName); // Task should be assigned to the only available instance which is participant2 Assert.assertTrue(TestHelper.verify( () -> (TaskPartitionState.RUNNING .equals(_driver.getJobContext(namespacedJobName).getPartitionState(0)) && (PARTICIPANT_PREFIX + "_" + (_startPort + 2)) .equals(_driver.getJobContext(namespacedJobName).getAssignedParticipant(0))), TestHelper.WAIT_DURATION)); // Now start two other participants startParticipant(0); startParticipant(1); // Get current state of participant 2 and make sure it is created String instanceP2 = PARTICIPANT_PREFIX + "_" + (_startPort + 2); ZkClient clientP2 = (ZkClient) _participants[2].getZkClient(); String sessionIdP2 = ZkTestHelper.getSessionId(clientP2); String currentStatePathP2 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP2, sessionIdP2, namespacedJobName).toString(); Assert .assertTrue( TestHelper .verify( () -> (_manager.getHelixDataAccessor().getBaseDataAccessor() .get(currentStatePathP2, new Stat(), AccessOption.PERSISTENT) != null), TestHelper.WAIT_DURATION)); // Set the current state of participant0 and participant1 with requested state equals DROPPED String instanceP0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); ZkClient clientP0 = (ZkClient) _participants[0].getZkClient(); String sessionIdP0 = ZkTestHelper.getSessionId(clientP0); String currentStatePathP0 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP0, sessionIdP0, namespacedJobName).toString(); String instanceP1 = PARTICIPANT_PREFIX + "_" + (_startPort + 1); ZkClient clientP1 = (ZkClient) _participants[1].getZkClient(); String sessionIdP1 = ZkTestHelper.getSessionId(clientP1); String currentStatePathP1 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP1, sessionIdP1, namespacedJobName).toString(); ZNRecord record = _manager.getHelixDataAccessor().getBaseDataAccessor().get(currentStatePathP2, new Stat(), AccessOption.PERSISTENT); String partitionName = namespacedJobName + "_0"; Map<String, String> newCurrentState = new HashMap<>(); newCurrentState.put(CurrentState.CurrentStateProperty.CURRENT_STATE.name(), TaskPartitionState.RUNNING.name()); newCurrentState.put(CurrentState.CurrentStateProperty.REQUESTED_STATE.name(), TaskPartitionState.DROPPED.name()); record.setSimpleField(CurrentState.CurrentStateProperty.SESSION_ID.name(), sessionIdP0); record.setMapField(partitionName, newCurrentState); _manager.getHelixDataAccessor().getBaseDataAccessor().set(currentStatePathP0, record, AccessOption.PERSISTENT); record.setSimpleField(CurrentState.CurrentStateProperty.SESSION_ID.name(), sessionIdP1); _manager.getHelixDataAccessor().getBaseDataAccessor().set(currentStatePathP1, record, AccessOption.PERSISTENT); // Make sure that the current states on participant0 and participant1 have been deleted Assert .assertTrue( TestHelper .verify( () -> (_manager.getHelixDataAccessor().getBaseDataAccessor() .get(currentStatePathP0, new Stat(), AccessOption.PERSISTENT) == null && _manager.getHelixDataAccessor().getBaseDataAccessor() .get(currentStatePathP1, new Stat(), AccessOption.PERSISTENT) == null), TestHelper.WAIT_DURATION)); _driver.stop(workflowName); } @Test(dependsOnMethods = "testDropCurrentStateRunningTask") public void testJobCurrentStateDroppedAfterCompletion() throws Exception { // Stop participants that have been started in previous test and start one of them for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } _participants = new MockParticipantManager[_numNodes]; startParticipant(0); String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilderCompleted = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG).setMaxAttemptsPerTask(1) .setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10")); // Task gets timed out in 10 seconds because the the default value is 10 seconds in // DEFAULT_JOB_CONFIG JobConfig.Builder jobBuilderTimedOut = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG).setMaxAttemptsPerTask(1) .setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName, 0, 100); for (int i = 0; i < 20; i++) { jobQueue.enqueueJob("job" + i, jobBuilderCompleted); } jobQueue.enqueueJob("job" + 20, jobBuilderTimedOut); _driver.start(jobQueue.build()); for (int i = 0; i < 20; i++) { _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job" + i), TaskState.COMPLETED); } _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job" + 20), TaskState.FAILED); String instanceP0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); ZkClient clientP0 = (ZkClient) _participants[0].getZkClient(); String sessionIdP0 = ZkTestHelper.getSessionId(clientP0); for (int i = 0; i < 21; i++) { String currentStatePathP0 = "/" + CLUSTER_NAME + "/INSTANCES/" + instanceP0 + "/CURRENTSTATES/" + sessionIdP0 + "/" + TaskUtil.getNamespacedJobName(jobQueueName, "job" + i); boolean isCurrentStateRemoved = TestHelper.verify(() -> { ZNRecord record = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(currentStatePathP0, new Stat(), AccessOption.PERSISTENT); return record == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(isCurrentStateRemoved); } } }
9,634
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestDeleteWorkflow.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.HelixAdmin; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestDeleteWorkflow extends TaskTestBase { private static final long DELETE_DELAY = 5000L; private static final long FORCE_DELETE_BACKOFF = 200L; private HelixAdmin admin; @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; admin = _gSetupTool.getClusterManagementTool(); super.beforeClass(); } @Test public void testDeleteWorkflow() throws InterruptedException { String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("job1", jobBuilder); _driver.start(jobQueue.build()); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job1"), TaskState.IN_PROGRESS); // Check that WorkflowConfig, WorkflowContext, and IdealState are indeed created for this job // queue Assert.assertNotNull(_driver.getWorkflowConfig(jobQueueName)); Assert.assertNotNull(_driver.getWorkflowContext(jobQueueName)); // Pause the Controller so that the job queue won't get deleted admin.enableCluster(CLUSTER_NAME, false); Thread.sleep(1000); // Attempt the deletion and time out try { _driver.deleteAndWaitForCompletion(jobQueueName, DELETE_DELAY); Assert.fail( "Delete must time out and throw a HelixException with the Controller paused, but did not!"); } catch (HelixException e) { // Pass } // Resume the Controller and call delete again admin.enableCluster(CLUSTER_NAME, true); _driver.deleteAndWaitForCompletion(jobQueueName, DELETE_DELAY); // Check that the deletion operation completed Assert.assertNull(_driver.getWorkflowConfig(jobQueueName)); Assert.assertNull(_driver.getWorkflowContext(jobQueueName)); } @Test public void testDeleteWorkflowForcefully() throws InterruptedException { String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("job1", jobBuilder); _driver.start(jobQueue.build()); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job1"), TaskState.IN_PROGRESS); // Check that WorkflowConfig, WorkflowContext, JobConfig, and JobContext are indeed created for this job // queue Assert.assertNotNull(_driver.getWorkflowConfig(jobQueueName)); Assert.assertNotNull(_driver.getWorkflowContext(jobQueueName)); Assert.assertNotNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); Assert .assertNotNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); // Pause the Controller so that the job queue won't get deleted admin.enableCluster(CLUSTER_NAME, false); Thread.sleep(1000); // Attempt the deletion and time out try { _driver.deleteAndWaitForCompletion(jobQueueName, DELETE_DELAY); Assert.fail( "Delete must time out and throw a HelixException with the Controller paused, but did not!"); } catch (HelixException e) { // Pass } // delete forcefully _driver.delete(jobQueueName, true); Assert.assertNull(_driver.getWorkflowConfig(jobQueueName)); Assert.assertNull(_driver.getWorkflowContext(jobQueueName)); Assert.assertNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); Assert.assertNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); } @Test public void testDeleteHangingJobs() throws InterruptedException { String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("job1", jobBuilder); _driver.start(jobQueue.build()); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job1"), TaskState.IN_PROGRESS); // Check that WorkflowConfig and WorkflowContext are indeed created for this job queue Assert.assertNotNull(_driver.getWorkflowConfig(jobQueueName)); Assert.assertNotNull(_driver.getWorkflowContext(jobQueueName)); Assert.assertNotNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); Assert .assertNotNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); // Delete the workflowconfig and context of workflow HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuild = accessor.keyBuilder(); accessor.removeProperty(keyBuild.resourceConfig(jobQueueName)); accessor.removeProperty(keyBuild.workflowContext(jobQueueName)); BestPossibleExternalViewVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME) .setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(verifier.verifyByPolling()); // Sometimes it's a ZK write fail - delete one more time to lower test failure rate if (_driver.getWorkflowConfig(jobQueueName) != null || _driver.getWorkflowContext(jobQueueName) != null) { accessor.removeProperty(keyBuild.resourceConfig(jobQueueName)); accessor.removeProperty(keyBuild.workflowContext(jobQueueName)); } Assert.assertNull(_driver.getWorkflowConfig(jobQueueName)); Assert.assertNull(_driver.getWorkflowContext(jobQueueName)); // Attempt to delete the job and it should fail with exception. try { _driver.deleteJob(jobQueueName, "job1"); Assert.fail("Delete must be rejected and throw a HelixException, but did not!"); } catch (IllegalArgumentException e) { // Pass } // delete forcefully a few times with a backoff (the controller may write back the ZNodes // because force delete does not remove the job from the cache) for (int i = 0; i < 3; i++) { try { _driver.deleteJob(jobQueueName, "job1", true); } catch (Exception e) { // Multiple delete calls are okay } Thread.sleep(FORCE_DELETE_BACKOFF); } Assert.assertNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); Assert.assertNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1"))); } }
9,635
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestQuotaBasedScheduling.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.google.common.collect.Maps; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.ClusterConfig; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.assigner.AssignableInstance; import org.apache.helix.tools.ClusterSetup; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestQuotaBasedScheduling extends TaskTestBase { private static final String DEFAULT_QUOTA_TYPE = "DEFAULT"; private static final String JOB_COMMAND = "DummyCommand"; private Map<String, String> _jobCommandMap; private final Map<String, Integer> _quotaTypeExecutionCount = new ConcurrentHashMap<>(); private Set<String> _availableQuotaTypes = Collections.newSetFromMap(new ConcurrentHashMap<>()); private boolean _finishTask = false; @BeforeClass public void beforeClass() throws Exception { _numNodes = 2; // For easier debugging by inspecting ZNodes _participants = new MockParticipantManager[_numNodes]; String namespace = "/" + CLUSTER_NAME; if (_gZkClient.exists(namespace)) { _gZkClient.deleteRecursively(namespace); } // Setup cluster and instances ClusterSetup setupTool = new ClusterSetup(ZK_ADDR); setupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < _numNodes; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (_startPort + i); setupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } // start dummy participants for (int i = 0; i < _numNodes; i++) { final String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); // Set task callbacks Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); TaskFactory shortTaskFactory = context -> new ShortTask(context, instanceName); TaskFactory longTaskFactory = context -> new LongTask(context, instanceName); TaskFactory failTaskFactory = context -> new FailTask(context, instanceName); taskFactoryReg.put("ShortTask", shortTaskFactory); taskFactoryReg.put("LongTask", longTaskFactory); taskFactoryReg.put("FailTask", failTaskFactory); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } // Start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // Start an admin connection _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _driver = new TaskDriver(_manager); _jobCommandMap = Maps.newHashMap(); } @BeforeMethod public void beforeMethod() { _quotaTypeExecutionCount.clear(); _availableQuotaTypes.clear(); _finishTask = false; } /** * Tests whether jobs can run successfully without quotaTypes or quota configuration defined in * ClusterConfig. This test is to ensure backward-compatibility. This test must go first because * we want to make sure there is no quota config set anywhere. * @throws InterruptedException */ @Test public void testSchedulingWithoutQuota() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(true); workflowBuilder.setWorkflowConfig(configBuilder.build()); for (int i = 0; i < 10; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("ShortTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand(JOB_COMMAND) .addTaskConfigs(taskConfigs).setJobCommandConfigMap(_jobCommandMap); workflowBuilder.addJob("JOB" + i, jobConfigBulider); } _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); for (int i = 0; i < 10; i++) { String jobName = workflowName + "_" + "JOB" + i; TaskState jobState = _driver.getWorkflowContext(workflowName).getJobState(jobName); Assert.assertEquals(jobState, TaskState.COMPLETED); } } /** * Tests whether jobs with undefined types (not found in ClusterConfig) run as DEFAULT. * @throws InterruptedException */ @Test(dependsOnMethods = "testSchedulingWithoutQuota") public void testSchedulingUndefinedTypes() throws InterruptedException { ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 1); clusterConfig.setTaskQuotaRatio("A", 1); clusterConfig.setTaskQuotaRatio("B", 1); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); _availableQuotaTypes = clusterConfig.getTaskQuotaRatioMap().keySet(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(true); workflowBuilder.setWorkflowConfig(configBuilder.build()); for (int i = 0; i < 10; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("ShortTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand(JOB_COMMAND).addTaskConfigs(taskConfigs) .setJobCommandConfigMap(_jobCommandMap).setJobType("UNDEFINED"); workflowBuilder.addJob("JOB" + i, jobConfigBulider); } _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); // Check run counts for each quota type Assert.assertEquals((int) _quotaTypeExecutionCount.get("DEFAULT"), 10); Assert.assertFalse(_quotaTypeExecutionCount.containsKey("A")); Assert.assertFalse(_quotaTypeExecutionCount.containsKey("B")); } /** * Tests whether jobs with quotas can run successfully. * @throws InterruptedException */ @Test(dependsOnMethods = "testSchedulingWithoutQuota") public void testSchedulingWithQuota() throws InterruptedException { ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 1); clusterConfig.setTaskQuotaRatio("A", 1); clusterConfig.setTaskQuotaRatio("B", 1); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); _availableQuotaTypes = clusterConfig.getTaskQuotaRatioMap().keySet(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(true); workflowBuilder.setWorkflowConfig(configBuilder.build()); for (int i = 0; i < 5; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("ShortTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand(JOB_COMMAND) .addTaskConfigs(taskConfigs).setJobCommandConfigMap(_jobCommandMap).setJobType("A"); workflowBuilder.addJob("JOB" + i, jobConfigBulider); } for (int i = 5; i < 10; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("ShortTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand(JOB_COMMAND) .addTaskConfigs(taskConfigs).setJobCommandConfigMap(_jobCommandMap).setJobType("B"); workflowBuilder.addJob("JOB" + i, jobConfigBulider); } _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); // Check job states for (int i = 0; i < 10; i++) { String jobName = workflowName + "_" + "JOB" + i; TaskState jobState = _driver.getWorkflowContext(workflowName).getJobState(jobName); Assert.assertEquals(jobState, TaskState.COMPLETED); } // Check run counts for each quota type Assert.assertEquals((int) _quotaTypeExecutionCount.get("A"), 5); Assert.assertEquals((int) _quotaTypeExecutionCount.get("B"), 5); Assert.assertFalse(_quotaTypeExecutionCount.containsKey(DEFAULT_QUOTA_TYPE)); } @Test(dependsOnMethods = "testSchedulingWithoutQuota") public void testQuotaConfigChange() throws InterruptedException { ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 38); clusterConfig.setTaskQuotaRatio("A", 1); clusterConfig.setTaskQuotaRatio("B", 1); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); // 2 nodes - create 4 workflows with LongTask so that only 2 would get scheduled and run for (int i = 0; i < 4; i++) { String workflowName = TestHelper.getTestMethodName() + "_" + i; _driver.start(createWorkflow(workflowName, true, "A", 1, 1, "LongTask")); Thread.sleep(500L); } // Test that only 2 of the workflows are executed for (int i = 0; i < 2; i++) { String workflowName = TestHelper.getTestMethodName() + "_" + i; _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); } // Test that the next two are not executing JobContext context_2 = _driver.getJobContext("testQuotaConfigChange_2_testQuotaConfigChange_2_0"); JobContext context_3 = _driver.getJobContext("testQuotaConfigChange_3_testQuotaConfigChange_3_0"); Assert.assertNull(context_2.getPartitionState(0)); Assert.assertNull(context_3.getPartitionState(0)); // Change the quota config so that the rest of the workflows are in progress clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 1); clusterConfig.setTaskQuotaRatio("A", 38); clusterConfig.setTaskQuotaRatio("B", 1); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); // Wait for the change to propagate through and test that the next two are not executing Thread.sleep(1000L); context_2 = _driver.getJobContext("testQuotaConfigChange_2_testQuotaConfigChange_2_0"); context_3 = _driver.getJobContext("testQuotaConfigChange_3_testQuotaConfigChange_3_0"); Assert.assertNotNull(context_2.getPartitionState(0)); Assert.assertNotNull(context_3.getPartitionState(0)); } /** * Tests that quota ratios are being observed. This is done by creating short tasks for some quota * types and long tasks for some quota types. * @throws InterruptedException */ @Test(dependsOnMethods = "testSchedulingWithoutQuota") public void testSchedulingQuotaBottleneck() throws InterruptedException { ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 1); clusterConfig.setTaskQuotaRatio("A", 10); clusterConfig.setTaskQuotaRatio("B", 10); clusterConfig.setTaskQuotaRatio("C", 9); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); _availableQuotaTypes = clusterConfig.getTaskQuotaRatioMap().keySet(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(true); workflowBuilder.setWorkflowConfig(configBuilder.build()); // Create 3 jobs, 2 jobs of quotaType A and B with ShortTasks and 1 job of quotaType B with // LongTasks // JOB_A List<TaskConfig> taskConfigsA = new ArrayList<>(); for (int i = 0; i < 20; i++) { Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigsA.add(new TaskConfig("ShortTask", taskConfigMap)); } JobConfig.Builder jobBuilderA = new JobConfig.Builder().setCommand(JOB_COMMAND).setJobCommandConfigMap(_jobCommandMap) .addTaskConfigs(taskConfigsA).setJobType("A").setNumConcurrentTasksPerInstance(20); workflowBuilder.addJob("JOB_A", jobBuilderA); // JOB_B List<TaskConfig> taskConfigsB = new ArrayList<>(); for (int i = 0; i < 20; i++) { Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigsB.add(new TaskConfig("ShortTask", taskConfigMap)); } JobConfig.Builder jobBuilderB = new JobConfig.Builder().setCommand(JOB_COMMAND).setJobCommandConfigMap(_jobCommandMap) .addTaskConfigs(taskConfigsB).setJobType("B").setNumConcurrentTasksPerInstance(20); workflowBuilder.addJob("JOB_B", jobBuilderB); // JOB_C List<TaskConfig> taskConfigsC = new ArrayList<>(); for (int i = 0; i < 20; i++) { Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigsC.add(new TaskConfig("LongTask", taskConfigMap)); } JobConfig.Builder jobBuilderC = new JobConfig.Builder().setCommand(JOB_COMMAND).setJobCommandConfigMap(_jobCommandMap) .addTaskConfigs(taskConfigsC).setJobType("C").setNumConcurrentTasksPerInstance(20); workflowBuilder.addJob("JOB_C", jobBuilderC); _driver.start(workflowBuilder.build()); // Wait until JOB_A and JOB_B are done _driver.pollForJobState(workflowName, workflowName + "_JOB_A", TaskState.COMPLETED); _driver.pollForJobState(workflowName, workflowName + "_JOB_B", TaskState.COMPLETED); // At this point, JOB_C should still be in progress due to long-running tasks TaskState jobState = _driver.getWorkflowContext(workflowName).getJobState(workflowName + "_JOB_C"); Assert.assertEquals(jobState, TaskState.IN_PROGRESS); // Finish rest of the tasks _finishTask = true; } /** * Tests that in a single workflow, if there are multiple jobs with different quota types, one of * which is a long running quota type. * @throws InterruptedException */ @Test(dependsOnMethods = "testSchedulingWithoutQuota") public void testWorkflowStuck() throws InterruptedException { ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 10); clusterConfig.setTaskQuotaRatio("A", 10); clusterConfig.setTaskQuotaRatio("B", 10); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); _availableQuotaTypes = clusterConfig.getTaskQuotaRatioMap().keySet(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(true); workflowBuilder.setWorkflowConfig(configBuilder.build()); // JOB_A List<TaskConfig> taskConfigsA = new ArrayList<>(); for (int i = 0; i < 50; i++) { Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigsA.add(new TaskConfig("LongTask", taskConfigMap)); } JobConfig.Builder jobBuilderA = new JobConfig.Builder().setCommand(JOB_COMMAND).setJobCommandConfigMap(_jobCommandMap) .addTaskConfigs(taskConfigsA).setJobType("A").setNumConcurrentTasksPerInstance(50); workflowBuilder.addJob("JOB_A", jobBuilderA); // JOB_B List<TaskConfig> taskConfigsB = new ArrayList<>(); for (int i = 0; i < 50; i++) { Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigsB.add(new TaskConfig("LongTask", taskConfigMap)); } JobConfig.Builder jobBuilderB = new JobConfig.Builder().setCommand(JOB_COMMAND).setJobCommandConfigMap(_jobCommandMap) .addTaskConfigs(taskConfigsB).setJobType("B").setNumConcurrentTasksPerInstance(50); workflowBuilder.addJob("JOB_B", jobBuilderB); // JOB_C (DEFAULT type) List<TaskConfig> taskConfigsC = new ArrayList<>(); for (int i = 0; i < 50; i++) { Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigsC.add(new TaskConfig("LongTask", taskConfigMap)); } JobConfig.Builder jobBuilderC = new JobConfig.Builder().setCommand(JOB_COMMAND) .setJobCommandConfigMap(_jobCommandMap).addTaskConfigs(taskConfigsC) .setJobType(DEFAULT_QUOTA_TYPE).setNumConcurrentTasksPerInstance(50); workflowBuilder.addJob("JOB_DEFAULT", jobBuilderC); _driver.start(workflowBuilder.build()); // Wait until jobs are all in progress and saturated the thread pool _driver.pollForJobState(workflowName, workflowName + "_JOB_A", TaskState.IN_PROGRESS); _driver.pollForJobState(workflowName, workflowName + "_JOB_B", TaskState.IN_PROGRESS); _driver.pollForJobState(workflowName, workflowName + "_JOB_DEFAULT", TaskState.IN_PROGRESS); // Submit another workflow to make sure this doesn't run when the thread pool is saturated Workflow secondWorkflow = createWorkflow("secondWorkflow", true, DEFAULT_QUOTA_TYPE, 1, 1, "ShortTask"); _driver.start(secondWorkflow); // At this point, secondWorkflow should still be in progress due to its task not being scheduled // due to thread pool saturation _driver.pollForWorkflowState("secondWorkflow", 2000L, TaskState.IN_PROGRESS); // Finish rest of the tasks _finishTask = true; } /** * Tests that by repeatedly scheduling workflows and jobs that there is no thread leak when there * are a multidude of successful and failed tests. The number of total tasks run must be well * above the number of total thread capacity. * Note: disabled because this is holding up mvn test due to its job/task load. * @throws InterruptedException */ @Test(dependsOnMethods = "testSchedulingWithoutQuota") public void testThreadLeak() throws InterruptedException { ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 1); clusterConfig.setTaskQuotaRatio("A", 1); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); _availableQuotaTypes = clusterConfig.getTaskQuotaRatioMap().keySet(); List<String> workflowNames = new ArrayList<>(); // A word about these numbers. Currently, numNodes is 2, meaning each instance will have 40 // threads, so we just need to make the total number of tasks well over 80 int numWorkflows = 40; int numJobs = 3; int numTasks = 3; for (int i = 0; i < numWorkflows; i++) { boolean shouldOverlapJobAssign = i % 3 == 1; // Alternate between true and false String quotaType = (i % 2 == 1) ? null : "A"; // Alternate between null (DEFAULT) and A String taskType = (i % 3 == 1) ? "FailTask" : "ShortTask"; // Some tasks will fail String workflowName = TestHelper.getTestMethodName() + "_" + i; workflowNames.add(workflowName); // For polling the state for these workflows Workflow workflow = createWorkflow(workflowName, shouldOverlapJobAssign, quotaType, numJobs, numTasks, taskType); _driver.start(workflow); } // Wait until all workflows finish for (String workflowName : workflowNames) { _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED, TaskState.ABORTED, TaskState.TIMED_OUT, TaskState.FAILED); } for (int i = 0; i < numWorkflows; i++) { String workflowName = workflowNames.get(i); TaskState state = (i % 3 == 1) ? TaskState.FAILED : TaskState.COMPLETED; Assert.assertEquals(TaskDriver.getWorkflowContext(_manager, workflowName).getWorkflowState(), state); } // Finish rest of the tasks _finishTask = true; } /** * Tests quota-based scheduling for a job queue with different quota types. * @throws InterruptedException */ @Test(dependsOnMethods = "testSchedulingWithoutQuota") public void testJobQueueScheduling() throws InterruptedException { // First define quota config ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME); clusterConfig.resetTaskQuotaRatioMap(); clusterConfig.setTaskQuotaRatio(DEFAULT_QUOTA_TYPE, 1); clusterConfig.setTaskQuotaRatio("A", 1); clusterConfig.setTaskQuotaRatio("B", 1); _manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig); _availableQuotaTypes = clusterConfig.getTaskQuotaRatioMap().keySet(); String queueName = TestHelper.getTestMethodName(); WorkflowConfig.Builder workflowConfigBuilder = new WorkflowConfig.Builder(queueName); workflowConfigBuilder.setParallelJobs(1); workflowConfigBuilder.setAllowOverlapJobAssignment(false); // Create a job queue JobQueue.Builder queueBuild = new JobQueue.Builder(queueName).setWorkflowConfig(workflowConfigBuilder.build()); JobQueue queue = queueBuild.build(); _driver.createQueue(queue); // Stop the queue to add jobs to the queue _driver.stop(queueName); // Keep track of the last jobName added String lastJobName = ""; // First run some jobs with quotaType A List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("ShortTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand(JOB_COMMAND) .addTaskConfigs(taskConfigs).setJobCommandConfigMap(_jobCommandMap).setJobType("A"); for (int i = 0; i < 5; i++) { String jobName = "JOB_" + i; lastJobName = jobName; _driver.enqueueJob(queueName, jobName, jobConfigBulider); } // Resume the queue briefly and stop again to add more jobs _driver.resume(queueName); _driver.stop(queueName); // Run some jobs with quotaType B // First run some jobs with quotaType A taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("ShortTask", new HashMap<>())); jobConfigBulider = new JobConfig.Builder().setCommand(JOB_COMMAND).addTaskConfigs(taskConfigs) .setJobCommandConfigMap(_jobCommandMap).setJobType("B"); for (int i = 5; i < 10; i++) { String jobName = "JOB_" + i; lastJobName = jobName; _driver.enqueueJob(queueName, jobName, jobConfigBulider); } _driver.resume(queueName); _driver.pollForJobState(queueName, queueName + "_" + lastJobName, TaskState.COMPLETED); // Check run counts for each quota type Assert.assertEquals((int) _quotaTypeExecutionCount.get("A"), 5); Assert.assertEquals((int) _quotaTypeExecutionCount.get("B"), 5); Assert.assertFalse(_quotaTypeExecutionCount.containsKey(DEFAULT_QUOTA_TYPE)); // Finish rest of the tasks _finishTask = true; } /** * Helper method for creating custom workflows. * @param workflowName * @param shouldOverlapJobAssign * @param quotaType * @param numJobs * @param numTasks * @param taskType * @return a workflow per parameters given */ private Workflow createWorkflow(String workflowName, boolean shouldOverlapJobAssign, String quotaType, int numJobs, int numTasks, String taskType) { Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(shouldOverlapJobAssign); workflowBuilder.setWorkflowConfig(configBuilder.build()); for (int jobIndex = 0; jobIndex < numJobs; jobIndex++) { String jobName = workflowName + "_" + jobIndex; List<TaskConfig> taskConfigs = new ArrayList<>(); for (int taskIndex = 0; taskIndex < numTasks; taskIndex++) { Map<String, String> taskConfigMap = new HashMap<>(); taskConfigs.add(new TaskConfig(taskType, taskConfigMap)); } JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(JOB_COMMAND) .setJobCommandConfigMap(_jobCommandMap).addTaskConfigs(taskConfigs).setJobType(quotaType); workflowBuilder.addJob(jobName, jobBuilder); } return workflowBuilder.build(); } /** * A mock task class that models a short-lived task. */ private class ShortTask extends MockTask { private final String _instanceName; private String _quotaType; ShortTask(TaskCallbackContext context, String instanceName) { super(context); _instanceName = instanceName; _quotaType = context.getJobConfig().getJobType(); if (_quotaType != null && !_availableQuotaTypes.contains(_quotaType)) { _quotaType = AssignableInstance.DEFAULT_QUOTA_TYPE; } // Initialize the count for this quotaType if not already done synchronized (_quotaTypeExecutionCount) { if (_quotaType != null && !_quotaTypeExecutionCount.containsKey(_quotaType)) { _quotaTypeExecutionCount.put(_quotaType, 0); } } } @Override public TaskResult run() { if (_quotaType != null) { synchronized (_quotaTypeExecutionCount) { _quotaTypeExecutionCount.put(_quotaType, _quotaTypeExecutionCount.get(_quotaType) + 1); } } return new TaskResult(TaskResult.Status.COMPLETED, generateInfoMessageForDebugging(_instanceName, _quotaType)); } } /** * A mock task class that models a long-running task. */ private class LongTask extends MockTask { private final String _instanceName; private String _quotaType; LongTask(TaskCallbackContext context, String instanceName) { super(context); _instanceName = instanceName; _quotaType = context.getJobConfig().getJobType(); if (_quotaType != null && !_availableQuotaTypes.contains(_quotaType)) { _quotaType = AssignableInstance.DEFAULT_QUOTA_TYPE; } // Initialize the count for this quotaType if not already done if (_quotaType != null && !_quotaTypeExecutionCount.containsKey(_quotaType)) { synchronized (_quotaTypeExecutionCount) { _quotaTypeExecutionCount.put(_quotaType, 0); } } } @Override public TaskResult run() { if (_quotaType != null) { synchronized (_quotaTypeExecutionCount) { _quotaTypeExecutionCount.put(_quotaType, _quotaTypeExecutionCount.get(_quotaType) + 1); } } // Only take long if finishTask is false while (!_finishTask) { try { Thread.sleep(200L); } catch (InterruptedException e) { e.printStackTrace(); } } return new TaskResult(TaskResult.Status.COMPLETED, generateInfoMessageForDebugging(_instanceName, _quotaType)); } } /** * A mock task class that models a failed task. */ private class FailTask extends MockTask { private final String _instanceName; private String _quotaType; FailTask(TaskCallbackContext context, String instanceName) { super(context); _instanceName = instanceName; _quotaType = context.getJobConfig().getJobType(); if (_quotaType != null && !_availableQuotaTypes.contains(_quotaType)) { _quotaType = AssignableInstance.DEFAULT_QUOTA_TYPE; } // Initialize the count for this quotaType if not already done if (_quotaType != null && !_quotaTypeExecutionCount.containsKey(_quotaType)) { synchronized (_quotaTypeExecutionCount) { _quotaTypeExecutionCount.put(_quotaType, 0); } } } @Override public TaskResult run() { if (_quotaType != null) { synchronized (_quotaTypeExecutionCount) { _quotaTypeExecutionCount.put(_quotaType, _quotaTypeExecutionCount.get(_quotaType) + 1); } } return new TaskResult(TaskResult.Status.FAILED, generateInfoMessageForDebugging(_instanceName, _quotaType)); } } /** * Helper method for generating info string for debugging purposes. * @param instanceName * @param quotaType * @return */ private String generateInfoMessageForDebugging(String instanceName, String quotaType) { return String.format("Instance: %s, quotaType: %s", instanceName, quotaType); } }
9,636
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestRecurringJobQueue.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.HelixDataAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TargetState; import org.apache.helix.task.TaskState; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; public class TestRecurringJobQueue extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestRecurringJobQueue.class); @Test public void deleteRecreateRecurrentQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName); List<String> currentJobNames = createAndEnqueueJob(queueBuild, 2); queueBuild.setExpiry(1); _driver.start(queueBuild.build()); WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); // ensure job 1 is started before stop it String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); String namedSpaceJob1 = String.format("%s_%s", scheduledQueue, currentJobNames.get(0)); _driver.pollForJobState(scheduledQueue, namedSpaceJob1, TaskState.IN_PROGRESS); _driver.stop(queueName); _driver.deleteAndWaitForCompletion(queueName, 5000); JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName, 5); currentJobNames.clear(); currentJobNames = createAndEnqueueJob(queueBuilder, 2); _driver.start(queueBuilder.build()); // ensure jobs are started and completed scheduledQueue = null; while (scheduledQueue == null) { wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); } namedSpaceJob1 = String.format("%s_%s", scheduledQueue, currentJobNames.get(0)); _driver.pollForJobState(scheduledQueue, namedSpaceJob1, TaskState.COMPLETED); scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); String namedSpaceJob2 = String.format("%s_%s", scheduledQueue, currentJobNames.get(1)); _driver.pollForJobState(scheduledQueue, namedSpaceJob2, TaskState.COMPLETED); } @Test public void stopDeleteJobAndResumeRecurrentQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName, 5); // Create and Enqueue jobs Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(500)); Thread.sleep(100); List<String> currentJobNames = createAndEnqueueJob(queueBuilder, 5); _driver.createQueue(queueBuilder.build()); WorkflowContext wCtx = null; String scheduledQueue = null; while (scheduledQueue == null) { wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); } // ensure job 1 is started before deleting it String deletedJob1 = currentJobNames.get(0); String namedSpaceDeletedJob1 = String.format("%s_%s", scheduledQueue, deletedJob1); _driver.pollForJobState(scheduledQueue, namedSpaceDeletedJob1, TaskState.IN_PROGRESS, TaskState.COMPLETED); // stop the queue LOG.info("Pausing job-queue: " + scheduledQueue); _driver.stop(queueName); _driver.pollForJobState(scheduledQueue, namedSpaceDeletedJob1, TaskState.STOPPED); _driver.pollForWorkflowState(scheduledQueue, TaskState.STOPPED); // delete the in-progress job (job 1) and verify it being deleted _driver.deleteJob(queueName, deletedJob1); verifyJobDeleted(queueName, namedSpaceDeletedJob1); verifyJobDeleted(scheduledQueue, namedSpaceDeletedJob1); LOG.info("Resuming job-queue: " + queueName); _driver.resume(queueName); // ensure job 2 is started _driver.pollForJobState(scheduledQueue, String.format("%s_%s", scheduledQueue, currentJobNames.get(1)), TaskState.IN_PROGRESS, TaskState.COMPLETED); // stop the queue LOG.info("Pausing job-queue: " + queueName); _driver.stop(queueName); _driver.pollForJobState(scheduledQueue, String.format("%s_%s", scheduledQueue, currentJobNames.get(1)), TaskState.STOPPED); _driver.pollForWorkflowState(scheduledQueue, TaskState.STOPPED); // Ensure job 3 is not started before deleting it String deletedJob2 = currentJobNames.get(2); String namedSpaceDeletedJob2 = String.format("%s_%s", scheduledQueue, deletedJob2); TaskTestUtil.pollForEmptyJobState(_driver, scheduledQueue, namedSpaceDeletedJob2); // delete not-started job (job 3) and verify it being deleted _driver.deleteJob(queueName, deletedJob2); verifyJobDeleted(queueName, namedSpaceDeletedJob2); verifyJobDeleted(scheduledQueue, namedSpaceDeletedJob2); LOG.info("Resuming job-queue: " + queueName); _driver.resume(queueName); // Ensure the jobs left are successful completed in the correct order currentJobNames.remove(deletedJob1); currentJobNames.remove(deletedJob2); long preJobFinish = 0; for (int i = 0; i < currentJobNames.size(); i++) { String namedSpaceJobName = String.format("%s_%s", scheduledQueue, currentJobNames.get(i)); _driver.pollForJobState(scheduledQueue, namedSpaceJobName, TaskState.COMPLETED); JobContext jobContext = _driver.getJobContext(namedSpaceJobName); long jobStart = jobContext.getStartTime(); Assert.assertTrue(jobStart >= preJobFinish); preJobFinish = jobContext.getFinishTime(); } // verify the job is not there for the next recurrence of queue schedule } @Test public void deleteJobFromRecurrentQueueNotStarted() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName); // create jobs List<JobConfig.Builder> jobs = new ArrayList<JobConfig.Builder>(); List<String> jobNames = new ArrayList<String>(); Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(500)); final int JOB_COUNTS = 3; for (int i = 0; i < JOB_COUNTS; i++) { String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; JobConfig.Builder job = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(commandConfig).setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(targetPartition)); jobs.add(job); jobNames.add(targetPartition.toLowerCase() + "Job" + i); } // enqueue all jobs except last one for (int i = 0; i < JOB_COUNTS - 1; ++i) { LOG.info("Enqueuing job: " + jobNames.get(i)); queueBuilder.enqueueJob(jobNames.get(i), jobs.get(i)); } _driver.createQueue(queueBuilder.build()); String currentLastJob = jobNames.get(JOB_COUNTS - 2); WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); // ensure all jobs are finished String namedSpaceJob = String.format("%s_%s", scheduledQueue, currentLastJob); _driver.pollForJobState(scheduledQueue, namedSpaceJob, TaskState.COMPLETED); // enqueue the last job LOG.info("Enqueuing job: " + jobNames.get(JOB_COUNTS - 1)); _driver.enqueueJob(queueName, jobNames.get(JOB_COUNTS - 1), jobs.get(JOB_COUNTS - 1)); _driver.stop(queueName); // remove the last job _driver.deleteJob(queueName, jobNames.get(JOB_COUNTS - 1)); // verify verifyJobDeleted(queueName, String.format("%s_%s", scheduledQueue, jobNames.get(JOB_COUNTS - 1))); } @Test public void testCreateStoppedQueue() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName, 0, 600000, TargetState.STOP); createAndEnqueueJob(queueBuild, 2); _driver.createQueue(queueBuild.build()); WorkflowConfig workflowConfig = _driver.getWorkflowConfig(queueName); Assert.assertEquals(workflowConfig.getTargetState(), TargetState.STOP); _driver.resume(queueName); // ensure LAST_SCHEDULED_WORKFLOW field is written to Zookeeper Assert.assertTrue(TestHelper.verify(() -> { WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); return wCtx.getLastScheduledSingleWorkflow() != null; }, TestHelper.WAIT_DURATION)); WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); _driver.pollForWorkflowState(wCtx.getLastScheduledSingleWorkflow(), TaskState.COMPLETED); } @Test public void testDeletingRecurrentQueueWithHistory() throws Exception { final String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName, 0, 60, TargetState.STOP); createAndEnqueueJob(queueBuild, 2); _driver.createQueue(queueBuild.build()); WorkflowConfig workflowConfig = _driver.getWorkflowConfig(queueName); Assert.assertEquals(workflowConfig.getTargetState(), TargetState.STOP); _driver.resume(queueName); WorkflowContext wCtx; // wait until at least 2 workflows are scheduled based on template queue do { Thread.sleep(60000L); wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); } while (wCtx.getScheduledWorkflows().size() < 2); // Stop recurring workflow _driver.stop(queueName); _driver.pollForWorkflowState(queueName, TaskState.STOPPED); // Record all scheduled workflows wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); List<String> scheduledWorkflows = new ArrayList<>(wCtx.getScheduledWorkflows()); final String lastScheduledWorkflow = wCtx.getLastScheduledSingleWorkflow(); // Delete recurrent workflow _driver.delete(queueName); Thread.sleep(500L); // Wait until recurrent workflow and the last scheduled workflow are cleaned up boolean result = TestHelper.verify(() -> { WorkflowContext wCtx1 = _driver.getWorkflowContext(queueName); WorkflowContext lastWfCtx = _driver.getWorkflowContext(lastScheduledWorkflow); return (wCtx1 == null && lastWfCtx == null); }, 5 * 1000); Assert.assertTrue(result); for (String scheduledWorkflow : scheduledWorkflows) { WorkflowContext scheduledWorkflowCtx = _driver.getWorkflowContext(scheduledWorkflow); WorkflowConfig scheduledWorkflowCfg = _driver.getWorkflowConfig(scheduledWorkflow); Assert.assertNull(scheduledWorkflowCtx); Assert.assertNull(scheduledWorkflowCfg); } } @Test public void testGetNoExistWorkflowConfig() { String randomName = "randomJob"; WorkflowConfig workflowConfig = _driver.getWorkflowConfig(randomName); Assert.assertNull(workflowConfig); JobConfig jobConfig = _driver.getJobConfig(randomName); Assert.assertNull(jobConfig); WorkflowContext workflowContext = _driver.getWorkflowContext(randomName); Assert.assertNull(workflowContext); JobContext jobContext = _driver.getJobContext(randomName); Assert.assertNull(jobContext); } private void verifyJobDeleted(String queueName, String jobName) throws Exception { HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Assert.assertNull(accessor.getProperty(keyBuilder.idealStates(jobName))); Assert.assertNull(accessor.getProperty(keyBuilder.resourceConfig(jobName))); TaskTestUtil.pollForEmptyJobState(_driver, queueName, jobName); } private List<String> createAndEnqueueJob(JobQueue.Builder queueBuild, int jobCount) { List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < jobCount; i++) { String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(targetPartition)); String jobName = targetPartition.toLowerCase() + "Job" + i; queueBuild.enqueueJob(jobName, jobConfig); currentJobNames.add(jobName); } Assert.assertEquals(currentJobNames.size(), jobCount); return currentJobNames; } }
9,637
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestDisableJobExternalView.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.common.collect.Sets; import org.apache.helix.ExternalViewChangeListener; import org.apache.helix.NotificationContext; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.model.ExternalView; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; public class TestDisableJobExternalView extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestDisableJobExternalView.class); /** * This test is no longer valid since Helix no longer computes ExternalView for Task Framework * resources. Contexts effectively serve as ExternalView for task resources. * **This test has been modified to test that there are no job-related resources appearing in * ExternalView** * @throws Exception */ @Test public void testJobsDisableExternalView() throws Exception { String queueName = TestHelper.getTestMethodName(); ExternviewChecker externviewChecker = new ExternviewChecker(); _manager.addExternalViewChangeListener(externviewChecker); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName); JobConfig.Builder job1 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet("SLAVE")); JobConfig.Builder job2 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet("SLAVE")).setDisableExternalView(true); JobConfig.Builder job3 = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet("MASTER")).setDisableExternalView(false); // enqueue jobs queueBuilder.enqueueJob("job1", job1); queueBuilder.enqueueJob("job2", job2); queueBuilder.enqueueJob("job3", job3); _driver.createQueue(queueBuilder.build()); // ensure all jobs are completed String namedSpaceJob3 = String.format("%s_%s", queueName, "job3"); _driver.pollForJobState(queueName, namedSpaceJob3, TaskState.COMPLETED); Set<String> seenExternalViews = externviewChecker.getSeenExternalViews(); String namedSpaceJob1 = String.format("%s_%s", queueName, "job1"); String namedSpaceJob2 = String.format("%s_%s", queueName, "job2"); Assert.assertTrue(!seenExternalViews.contains(namedSpaceJob1), "ExternalView found for " + namedSpaceJob1 + ". Jobs shouldn't be in EV!"); Assert.assertTrue(!seenExternalViews.contains(namedSpaceJob2), "External View for " + namedSpaceJob2 + " shoudld not exist!"); Assert.assertTrue(!seenExternalViews.contains(namedSpaceJob3), "ExternalView found for " + namedSpaceJob3 + ". Jobs shouldn't be in EV!"); _manager .removeListener(new PropertyKey.Builder(CLUSTER_NAME).externalViews(), externviewChecker); } private static class ExternviewChecker implements ExternalViewChangeListener { private Set<String> _seenExternalViews = new HashSet<String>(); @Override public void onExternalViewChange(List<ExternalView> externalViewList, NotificationContext changeContext) { for (ExternalView view : externalViewList) { _seenExternalViews.add(view.getResourceName()); } } public Set<String> getSeenExternalViews() { return _seenExternalViews; } } }
9,638
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskRebalancerFailover.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Set; import com.google.common.collect.Sets; import org.apache.helix.HelixDataAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.model.ExternalView; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobDag; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.WorkflowConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; public class TestTaskRebalancerFailover extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestTaskRebalancerFailover.class); @Test public void test() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue queue = new JobQueue.Builder(queueName).build(); _driver.createQueue(queue); _driver.stop(queue.getName()); _driver.pollForWorkflowState(queueName, TaskState.STOPPED); // Enqueue jobs Set<String> master = Sets.newHashSet("MASTER"); JobConfig.Builder job = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB).setTargetPartitionStates(master); String job1Name = "masterJob"; LOG.info("Enqueuing job: " + job1Name); _driver.enqueueJob(queueName, job1Name, job); _driver.resume(queue.getName()); // check all tasks completed on MASTER String namespacedJob1 = String.format("%s_%s", queueName, job1Name); _driver.pollForJobState(queueName, namespacedJob1, TaskState.COMPLETED); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); ExternalView ev = accessor.getProperty(keyBuilder.externalView(WorkflowGenerator.DEFAULT_TGT_DB)); JobContext ctx = _driver.getJobContext(namespacedJob1); Set<String> failOverPartitions = Sets.newHashSet(); for (int p = 0; p < _numPartitions; p++) { String instanceName = ctx.getAssignedParticipant(p); Assert.assertNotNull(instanceName); String partitionName = ctx.getTargetForPartition(p); Assert.assertNotNull(partitionName); String state = ev.getStateMap(partitionName).get(instanceName); Assert.assertNotNull(state); Assert.assertEquals(state, "MASTER"); if (instanceName.equals("localhost_12918")) { failOverPartitions.add(partitionName); } } // enqueue another master job and fail localhost_12918 String job2Name = "masterJob2"; String namespacedJob2 = String.format("%s_%s", queueName, job2Name); LOG.info("Enqueuing job: " + job2Name); _driver.enqueueJob(queueName, job2Name, job); _driver.pollForJobState(queueName, namespacedJob2, TaskState.IN_PROGRESS); _participants[0].syncStop(); _driver.pollForJobState(queueName, namespacedJob2, TaskState.COMPLETED); // tasks previously assigned to localhost_12918 should be re-scheduled on new master ctx = _driver.getJobContext(namespacedJob2); ev = accessor.getProperty(keyBuilder.externalView(WorkflowGenerator.DEFAULT_TGT_DB)); for (int p = 0; p < _numPartitions; p++) { String partitionName = ctx.getTargetForPartition(p); Assert.assertNotNull(partitionName); if (failOverPartitions.contains(partitionName)) { String instanceName = ctx.getAssignedParticipant(p); Assert.assertNotNull(instanceName); Assert.assertNotSame(instanceName, "localhost_12918"); String state = ev.getStateMap(partitionName).get(instanceName); Assert.assertNotNull(state); Assert.assertEquals(state, "MASTER"); } } // Flush queue and check cleanup _driver.flushQueue(queueName); Assert.assertNull(accessor.getProperty(keyBuilder.idealStates(namespacedJob1))); Assert.assertNull(accessor.getProperty(keyBuilder.resourceConfig(namespacedJob1))); Assert.assertNull(accessor.getProperty(keyBuilder.idealStates(namespacedJob2))); Assert.assertNull(accessor.getProperty(keyBuilder.resourceConfig(namespacedJob2))); WorkflowConfig workflowCfg = _driver.getWorkflowConfig(queueName); JobDag dag = workflowCfg.getJobDag(); Assert.assertFalse(dag.getAllNodes().contains(namespacedJob1)); Assert.assertFalse(dag.getAllNodes().contains(namespacedJob2)); Assert.assertFalse(dag.getChildrenToParents().containsKey(namespacedJob1)); Assert.assertFalse(dag.getChildrenToParents().containsKey(namespacedJob2)); Assert.assertFalse(dag.getParentsToChildren().containsKey(namespacedJob1)); Assert.assertFalse(dag.getParentsToChildren().containsKey(namespacedJob2)); } }
9,639
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobTimeout.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Map; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.ExternalView; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskSynchronizedTestBase; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public final class TestJobTimeout extends TaskSynchronizedTestBase { @BeforeClass public void beforeClass() throws Exception { _numNodes = 2; _numPartitions = 2; _numReplicas = 1; // only Master, no Slave _numDbs = 1; _participants = new MockParticipantManager[_numNodes]; _gSetupTool.addCluster(CLUSTER_NAME, true); setupParticipants(); setupDBs(); startParticipants(); createManagers(); _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); } @Test public void testTaskRunningIndefinitely() throws InterruptedException { // first job runs indefinitely and timeout, the second job runs successfully, the workflow // succeed. final String FIRST_JOB = "first_job"; final String SECOND_JOB = "second_job"; final String WORKFLOW_NAME = TestHelper.getTestMethodName(); final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB; JobConfig.Builder firstJobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")) // task stuck .setTimeout(2000L); JobConfig.Builder secondJobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setIgnoreDependentJobFailure(true); // ignore first // job's timeout WorkflowConfig.Builder workflowConfigBuilder = new WorkflowConfig.Builder(WORKFLOW_NAME).setFailureThreshold(1); // workflow ignores first // job's timeout and // schedule second job and // succeed. Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW_NAME) .setWorkflowConfig(workflowConfigBuilder.build()).addJob(FIRST_JOB, firstJobBuilder) .addJob(SECOND_JOB, secondJobBuilder).addParentChildDependency(FIRST_JOB, SECOND_JOB); _driver.start(workflowBuilder.build()); _driver.pollForJobState(WORKFLOW_NAME, TaskUtil.getNamespacedJobName(WORKFLOW_NAME, FIRST_JOB), TaskState.TIMED_OUT); _driver.pollForJobState(WORKFLOW_NAME, TaskUtil.getNamespacedJobName(WORKFLOW_NAME, SECOND_JOB), TaskState.COMPLETED); _driver.pollForWorkflowState(WORKFLOW_NAME, TaskState.COMPLETED); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, FIRST_JOB)); for (int pId : jobContext.getPartitionSet()) { // All tasks aborted because of job timeout Assert.assertEquals(jobContext.getPartitionState(pId), TaskPartitionState.TASK_ABORTED); } } @Test public void testNoSlaveToRunTask() throws InterruptedException { // first job can't be assigned to any instance and stuck, timeout, second job runs and workflow // succeed. final String FIRST_JOB = "first_job"; final String SECOND_JOB = "second_job"; final String WORKFLOW_NAME = TestHelper.getTestMethodName(); final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB; JobConfig.Builder firstJobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME) // since replica=1, there's no Slave, but target only Slave, the task can't be assigned, // job stuck and timeout .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.SLAVE.name())) .setCommand(MockTask.TASK_COMMAND).setTimeout(1000); JobConfig.Builder secondJobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setIgnoreDependentJobFailure(true); // ignore first // job's timeout WorkflowConfig.Builder workflowConfigBuilder = new WorkflowConfig.Builder(WORKFLOW_NAME).setFailureThreshold(1); // workflow ignores first // job's timeout and // schedule second job and // succeed. Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW_NAME) .setWorkflowConfig(workflowConfigBuilder.build()).addJob(FIRST_JOB, firstJobBuilder) .addJob(SECOND_JOB, secondJobBuilder).addParentChildDependency(FIRST_JOB, SECOND_JOB); // Check that there are no SLAVE replicas BestPossibleExternalViewVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(verifier.verifyByPolling()); ExternalView view = _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, DB_NAME); view.getPartitionSet().forEach(partition -> { for (Map.Entry<String, String> entry : view.getStateMap(partition).entrySet()) { if (!entry.getValue().equals("MASTER")) { try { Thread.sleep(2000L); } catch (InterruptedException e) { // OK } } } }); _driver.start(workflowBuilder.build()); _driver.pollForJobState(WORKFLOW_NAME, TaskUtil.getNamespacedJobName(WORKFLOW_NAME, FIRST_JOB), TaskState.TIMED_OUT); _driver.pollForJobState(WORKFLOW_NAME, TaskUtil.getNamespacedJobName(WORKFLOW_NAME, SECOND_JOB), TaskState.COMPLETED); _driver.pollForWorkflowState(WORKFLOW_NAME, TaskState.COMPLETED); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, FIRST_JOB)); for (int pId : jobContext.getPartitionSet()) { // No task assigned for first job Assert.assertNull(jobContext.getPartitionState(pId)); } } }
9,640
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/MockTask.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 com.fasterxml.jackson.databind.ObjectMapper; import org.apache.helix.HelixException; import org.apache.helix.task.Task; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskResult; import org.apache.helix.task.UserContentStore; public class MockTask extends UserContentStore implements Task { public static final String TASK_COMMAND = "Reindex"; public static final String JOB_DELAY = "Delay"; public static final String TASK_RESULT_STATUS = "TaskResultStatus"; public static final String THROW_EXCEPTION = "ThrowException"; public static final String ERROR_MESSAGE = "ErrorMessage"; public static final String FAILURE_COUNT_BEFORE_SUCCESS = "FailureCountBeforeSuccess"; public static final String SUCCESS_COUNT_BEFORE_FAIL = "SuccessCountBeforeFail"; public static final String NOT_ALLOW_TO_CANCEL = "NotAllowToCancel"; public static final String TARGET_PARTITION_CONFIG = "TargetPartitionConfig"; private long _delay; private volatile boolean _notAllowToCancel; private volatile boolean _canceled; private TaskResult.Status _taskResultStatus; private boolean _throwException; private int _numOfFailBeforeSuccess; private int _numOfSuccessBeforeFail; private String _errorMsg; public static boolean _signalFail; public MockTask(TaskCallbackContext context) { Map<String, String> cfg = context.getJobConfig().getJobCommandConfigMap(); if (cfg == null) { cfg = new HashMap<>(); } TaskConfig taskConfig = context.getTaskConfig(); Map<String, String> taskConfigMap = taskConfig.getConfigMap(); if (taskConfigMap != null) { cfg.putAll(taskConfigMap); } _delay = cfg.containsKey(JOB_DELAY) ? Long.parseLong(cfg.get(JOB_DELAY)) : 100L; _notAllowToCancel = cfg.containsKey(NOT_ALLOW_TO_CANCEL) ? Boolean.parseBoolean(cfg.get(NOT_ALLOW_TO_CANCEL)) : false; _taskResultStatus = cfg.containsKey(TASK_RESULT_STATUS) ? TaskResult.Status.valueOf(cfg.get(TASK_RESULT_STATUS)) : TaskResult.Status.COMPLETED; _throwException = cfg.containsKey(THROW_EXCEPTION) ? Boolean.valueOf(cfg.containsKey(THROW_EXCEPTION)) : false; _numOfFailBeforeSuccess = cfg.containsKey(FAILURE_COUNT_BEFORE_SUCCESS) ? Integer.parseInt( cfg.get(FAILURE_COUNT_BEFORE_SUCCESS)) : 0; _numOfSuccessBeforeFail = cfg.containsKey(SUCCESS_COUNT_BEFORE_FAIL) ? Integer .parseInt(cfg.get(SUCCESS_COUNT_BEFORE_FAIL)) : Integer.MAX_VALUE; _errorMsg = cfg.containsKey(ERROR_MESSAGE) ? cfg.get(ERROR_MESSAGE) : null; setTargetPartitionsConfigs(cfg, taskConfig.getTargetPartition()); } // Override configs if there's config for specific target partitions private void setTargetPartitionsConfigs(Map<String, String> cfg, String targetPartition) { if (cfg.containsKey(TARGET_PARTITION_CONFIG)) { Map<String, Map<String, String>> targetPartitionConfigs = deserializeTargetPartitionConfig(cfg.get(TARGET_PARTITION_CONFIG)); if (targetPartitionConfigs.containsKey(targetPartition)) { Map<String, String> targetPartitionConfig = targetPartitionConfigs.get(targetPartition); if (targetPartitionConfig.containsKey(JOB_DELAY)) { _delay = Long.parseLong(targetPartitionConfig.get(JOB_DELAY)); } if (targetPartitionConfig.containsKey(TASK_RESULT_STATUS)) { _taskResultStatus = TaskResult.Status.valueOf(targetPartitionConfig.get(TASK_RESULT_STATUS)); } } } } public static String serializeTargetPartitionConfig(Map<String, Map<String, String>> config) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(config); } catch (IOException e) { throw new HelixException(e); } } private static Map<String, Map<String, String>> deserializeTargetPartitionConfig(String configString) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(configString, Map.class); } catch (IOException e) { throw new HelixException(e); } } @Override public TaskResult run() { long expiry = System.currentTimeMillis() + _delay; long timeLeft; while (System.currentTimeMillis() < expiry) { if (_canceled && !_notAllowToCancel) { timeLeft = expiry - System.currentTimeMillis(); return new TaskResult(TaskResult.Status.CANCELED, String.valueOf(timeLeft < 0 ? 0 : timeLeft)); } if (_signalFail) { return new TaskResult(TaskResult.Status.FAILED, "Signaled to fail."); } sleep(10); } timeLeft = expiry - System.currentTimeMillis(); if (_throwException) { _numOfFailBeforeSuccess--; if (_errorMsg == null) { _errorMsg = "Test failed"; } throw new RuntimeException(_errorMsg != null ? _errorMsg : "Test failed"); } if (getUserContent(SUCCESS_COUNT_BEFORE_FAIL, Scope.WORKFLOW) != null) { _numOfSuccessBeforeFail = Integer.parseInt(getUserContent(SUCCESS_COUNT_BEFORE_FAIL, Scope.WORKFLOW)); } putUserContent(SUCCESS_COUNT_BEFORE_FAIL, "" + --_numOfSuccessBeforeFail, Scope.WORKFLOW); if (_numOfFailBeforeSuccess > 0 || _numOfSuccessBeforeFail < 0){ _numOfFailBeforeSuccess--; throw new RuntimeException(_errorMsg != null ? _errorMsg : "Test failed"); } return new TaskResult(_taskResultStatus, _errorMsg != null ? _errorMsg : String.valueOf(timeLeft < 0 ? 0 : timeLeft)); } @Override public void cancel() { _canceled = true; } private static void sleep(long d) { try { Thread.sleep(d); } catch (InterruptedException e) { e.printStackTrace(); } } }
9,641
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobQueueCleanUp.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashSet; import java.util.Set; import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestJobQueueCleanUp extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); } @Test public void testJobQueueCleanUp() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(ImmutableMap.of(MockTask.SUCCESS_COUNT_BEFORE_FAIL, "2")); for (int i = 0; i < 5; i++) { builder.enqueueJob("JOB" + i, jobBuilder); } _driver.start(builder.build()); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.FAILED); _driver.cleanupQueue(queueName); Assert.assertEquals(_driver.getWorkflowConfig(queueName).getJobDag().size(), 0); } @Test(dependsOnMethods = "testJobQueueCleanUp") public void testJobQueueNotCleanupRunningJobs() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); for (int i = 0; i < 3; i++) { builder.enqueueJob("JOB" + i, jobBuilder); } builder.enqueueJob("JOB" + 3, jobBuilder.setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000000"))); builder.enqueueJob("JOB" + 4, jobBuilder); _driver.start(builder.build()); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 3), TaskState.IN_PROGRESS); _driver.cleanupQueue(queueName); Assert.assertEquals(_driver.getWorkflowConfig(queueName).getJobDag().size(), 2); } @Test(dependsOnMethods = "testJobQueueNotCleanupRunningJobs") public void testJobQueueAutoCleanUp() throws Exception { int capacity = 10; String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName, capacity); WorkflowConfig.Builder cfgBuilder = new WorkflowConfig.Builder(builder.getWorkflowConfig()); cfgBuilder.setJobPurgeInterval(1000); builder.setWorkflowConfig(cfgBuilder.build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2).setJobCommandConfigMap( ImmutableMap.of(MockTask.SUCCESS_COUNT_BEFORE_FAIL, String.valueOf(capacity / 2))) .setExpiry(200L); Set<String> deletedJobs = new HashSet<String>(); Set<String> remainJobs = new HashSet<String>(); for (int i = 0; i < capacity; i++) { builder.enqueueJob("JOB" + i, jobBuilder); if (i < capacity/2) { deletedJobs.add("JOB" + i); } else { remainJobs.add(TaskUtil.getNamespacedJobName(queueName, "JOB" + i)); } } _driver.start(builder.build()); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + (capacity - 1)), TaskState.FAILED); Assert .assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(queueName); return config.getJobDag().getAllNodes().equals(remainJobs); }, TestHelper.WAIT_DURATION)); Assert.assertTrue(TestHelper.verify(() -> { WorkflowContext context = _driver.getWorkflowContext(queueName); return context.getJobStates().keySet().equals(remainJobs) && remainJobs .containsAll(context.getJobStartTimes().keySet()); }, TestHelper.WAIT_DURATION)); for (String job : deletedJobs) { JobConfig cfg = _driver.getJobConfig(job); JobContext ctx = _driver.getJobContext(job); Assert.assertNull(cfg); Assert.assertNull(ctx); } } @Test(dependsOnMethods = "testJobQueueAutoCleanUp") public void testJobQueueFailedCleanUp() throws Exception { int capacity = 10; String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName, capacity); WorkflowConfig.Builder cfgBuilder = new WorkflowConfig.Builder(builder.getWorkflowConfig()); cfgBuilder.setJobPurgeInterval(1000); builder.setWorkflowConfig(cfgBuilder.build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2).setJobCommandConfigMap( ImmutableMap.of(MockTask.SUCCESS_COUNT_BEFORE_FAIL, "0")) .setExpiry(200L).setTerminalStateExpiry(200L); for (int i = 0; i < capacity; i++) { builder.enqueueJob("JOB" + i, jobBuilder); } _driver.start(builder.build()); Assert.assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(queueName); return config.getJobDag().getAllNodes().isEmpty(); }, TestHelper.WAIT_DURATION)); Assert.assertTrue(TestHelper.verify(() -> { WorkflowContext context = _driver.getWorkflowContext(queueName); return context.getJobStates().isEmpty(); }, TestHelper.WAIT_DURATION)); } @Test(dependsOnMethods = "testJobQueueFailedCleanUp") public void testJobQueueTimedOutCleanUp() throws Exception { int capacity = 10; String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName, capacity); WorkflowConfig.Builder cfgBuilder = new WorkflowConfig.Builder(builder.getWorkflowConfig()); cfgBuilder.setJobPurgeInterval(1000); builder.setWorkflowConfig(cfgBuilder.build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2).setTimeout(100) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")) .setTerminalStateExpiry(200L); for (int i = 0; i < capacity; i++) { builder.enqueueJob("JOB" + i, jobBuilder); } _driver.start(builder.build()); Assert.assertTrue(TestHelper.verify(() -> { WorkflowConfig config = _driver.getWorkflowConfig(queueName); return config.getJobDag().getAllNodes().isEmpty(); }, TestHelper.WAIT_DURATION)); Assert.assertTrue(TestHelper.verify(() -> { WorkflowContext context = _driver.getWorkflowContext(queueName); return context.getJobStates().isEmpty(); }, TestHelper.WAIT_DURATION)); } }
9,642
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestGenericJobs.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; public class TestGenericJobs extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestGenericJobs.class); @Test public void testGenericJobs() throws Exception { String queueName = TestHelper.getTestMethodName(); // Create a queue LOG.info("Starting job-queue: " + queueName); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName); // Create and Enqueue jobs int num_jobs = 4; List<String> currentJobNames = new ArrayList<String>(); for (int i = 0; i < num_jobs; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder(); // create each task configs. List<TaskConfig> taskConfigs = new ArrayList<TaskConfig>(); int num_tasks = 10; for (int j = 0; j < num_tasks; j++) { taskConfigs.add( new TaskConfig.Builder().setTaskId("task_" + j).setCommand(MockTask.TASK_COMMAND) .build()); } jobConfig.addTaskConfigs(taskConfigs); String jobName = "job_" + i; queueBuilder.enqueueJob(jobName, jobConfig); currentJobNames.add(jobName); } _driver.start(queueBuilder.build()); String namedSpaceJob = String.format("%s_%s", queueName, currentJobNames.get(currentJobNames.size() - 1)); _driver.pollForJobState(queueName, namedSpaceJob, TaskState.COMPLETED); } }
9,643
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskCurrentStateDrop.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.AccessOption; import org.apache.helix.HelixDataAccessor; import org.apache.helix.TestHelper; import org.apache.helix.ZkTestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; /** * This test makes sure that the Current State of the task are being removed after participant * handles new session. */ public class TestTaskCurrentStateDrop extends TaskTestBase { private static final String DATABASE = WorkflowGenerator.DEFAULT_TGT_DB; protected HelixDataAccessor _accessor; @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; _numNodes = 1; super.beforeClass(); } @AfterClass() public void afterClass() throws Exception { super.afterClass(); } @Test public void testCurrentStateDropAfterReconnecting() throws Exception { String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder0 = new JobConfig.Builder().setWorkflow(jobQueueName).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("JOB0", jobBuilder0); _driver.start(jobQueue.build()); String namespacedJobName = TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"); _driver.pollForJobState(jobQueueName, namespacedJobName, TaskState.IN_PROGRESS); // Make sure task is in running state Assert.assertTrue(TestHelper.verify( () -> (TaskPartitionState.RUNNING .equals(_driver.getJobContext(namespacedJobName).getPartitionState(0))), TestHelper.WAIT_DURATION)); // Get the current states of Participant0 String instanceP0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); ZkClient clientP0 = (ZkClient) _participants[0].getZkClient(); String sessionIdP0 = ZkTestHelper.getSessionId(clientP0); String taskCurrentStatePathP0 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP0, sessionIdP0, namespacedJobName).toString(); String dataBaseCurrentStatePathP0 = _manager.getHelixDataAccessor().keyBuilder() .currentState(instanceP0, sessionIdP0, DATABASE).toString(); // Read the current states of Participant0 and make sure they been created boolean isCurrentStateCreated = TestHelper.verify(() -> { ZNRecord recordTask = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(taskCurrentStatePathP0, new Stat(), AccessOption.PERSISTENT); ZNRecord recordDataBase = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(dataBaseCurrentStatePathP0, new Stat(), AccessOption.PERSISTENT); return (recordTask != null && recordDataBase != null); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isCurrentStateCreated); // Stop the controller to make sure controller does not sent any message to participants inorder // to drop the current states _controller.syncStop(); // restart the participant0 and make sure task related current state has not been carried over stopParticipant(0); startParticipant(0); clientP0 = (ZkClient) _participants[0].getZkClient(); String newSessionIdP0 = ZkTestHelper.getSessionId(clientP0); String newTaskCurrentStatePathP0 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP0, newSessionIdP0, namespacedJobName).toString(); String newDataBaseCurrentStatePathP0 = _manager.getHelixDataAccessor().keyBuilder() .currentState(instanceP0, newSessionIdP0, DATABASE).toString(); boolean isCurrentStateExpected = TestHelper.verify(() -> { ZNRecord taskRecord = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(newTaskCurrentStatePathP0, new Stat(), AccessOption.PERSISTENT); ZNRecord dataBase = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(newDataBaseCurrentStatePathP0, new Stat(), AccessOption.PERSISTENT); return (taskRecord == null && dataBase != null); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isCurrentStateExpected); _driver.stop(jobQueueName); } @Test (dependsOnMethods = "testCurrentStateDropAfterReconnecting") public void testDropCurrentStateDisableInstance() throws Exception { // Start the Controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); String workflowName1 = TestHelper.getTestMethodName() + "_1"; String jobName = "JOB0"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName1).setNumberOfTasks(1) .setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName1).addJob(jobName, jobBuilder1); _driver.start(workflowBuilder1.build()); String namespacedJobName = TaskUtil.getNamespacedJobName(workflowName1, jobName); // Make sure current state and context are going to expected state of RUNNING String instanceP0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); ZkClient clientP0 = (ZkClient) _participants[0].getZkClient(); String sessionIdP0 = ZkTestHelper.getSessionId(clientP0); String currentStatePathP0 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP0, sessionIdP0, namespacedJobName).toString(); _driver.pollForJobState(workflowName1, namespacedJobName, TaskState.IN_PROGRESS); boolean isCurrentStateCreated = TestHelper.verify(() -> { ZNRecord record = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(currentStatePathP0, new Stat(), AccessOption.PERSISTENT); return record != null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(isCurrentStateCreated); Assert.assertTrue(TestHelper .verify(() -> (TaskPartitionState.RUNNING .equals(_driver.getJobContext(namespacedJobName) .getPartitionState(0))), TestHelper.WAIT_DURATION)); // Disable the instance and make sure the task current state is dropped String disabledInstance = _participants[0].getInstanceName(); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, disabledInstance, false); boolean isCurrentStateDeleted = TestHelper.verify(() -> { ZNRecord record = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(currentStatePathP0, new Stat(), AccessOption.PERSISTENT); return record == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(TestHelper .verify(() -> (TaskPartitionState.DROPPED .equals(_driver.getJobContext(namespacedJobName) .getPartitionState(0))), TestHelper.WAIT_DURATION)); Assert.assertTrue(isCurrentStateDeleted); // enable participant again and make sure task will be retried and number of attempts is increased _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, disabledInstance, true); Assert.assertTrue(TestHelper .verify(() -> (TaskPartitionState.RUNNING .equals(_driver.getJobContext(namespacedJobName) .getPartitionState(0)) && _driver.getJobContext(namespacedJobName) .getPartitionNumAttempts(0) == 2), TestHelper.WAIT_DURATION)); } }
9,644
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestDeleteJobFromJobQueue.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestDeleteJobFromJobQueue extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; super.beforeClass(); } @Test public void testForceDeleteJobFromJobQueue() throws InterruptedException { String jobQueueName = TestHelper.getTestMethodName(); // Create two jobs: job1 will complete fast, and job2 will be stuck in progress (taking a long // time to finish). The idea is to force-delete a stuck job (job2). JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10")); JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")).setTimeout(100000); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("job1", jobBuilder); jobQueue.enqueueJob("job2", jobBuilder2); _driver.start(jobQueue.build()); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job2"), TaskState.IN_PROGRESS); try { _driver.deleteJob(jobQueueName, "job2"); Assert.fail("Regular, non-force deleteJob should fail since the workflow is in progress!"); } catch (IllegalStateException e) { // Expect IllegalStateException because job2 is still in progress } // Check that the job ZNodes have not been deleted by regular deleteJob call Assert.assertNotNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job2"))); Assert .assertNotNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job2"))); // Force deletion can have Exception thrown as controller is writing to propertystore path too. // https://github.com/apache/helix/issues/1406, also force deletion may not be safe. // Thus, we stop pipeline to make sure there is not such race condition. _gSetupTool.getClusterManagementTool().enableCluster(CLUSTER_NAME, false); // note this sleep is critical as it would take time for controller to stop. // TODO: this is not best practice to sleep. Let GenericHelixController gives out a signal would // TODO: be another way. But this needs much more careful design. Thread.sleep(3000); _driver.deleteJob(jobQueueName, "job2", true); // Check that the job has been force-deleted (fully gone from ZK) Assert.assertNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job2"))); Assert.assertNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job2"))); } }
9,645
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestWorkflowContextWithoutConfig.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.AccessOption; import org.apache.helix.HelixDataAccessor; import org.apache.helix.TestHelper; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskUtil; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; /** * Test to check workflow context is not created without workflow config. * Test workflow context will be deleted if workflow config has been removed. */ public class TestWorkflowContextWithoutConfig extends TaskTestBase { @Test public void testWorkflowContextGarbageCollection() throws Exception { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder1 = createSimpleWorkflowBuilder(workflowName); _driver.start(builder1.build()); // Wait until workflow is created and IN_PROGRESS state. _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); // Check that WorkflowConfig and WorkflowContext are indeed created for this workflow Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); String workflowContextPath = "/" + CLUSTER_NAME + "/PROPERTYSTORE/TaskRebalancer/" + workflowName + "/Context"; ZNRecord record = _manager.getHelixDataAccessor().getBaseDataAccessor().get(workflowContextPath, null, AccessOption.PERSISTENT); Assert.assertNotNull(record); // Wait until workflow is completed. _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); // Verify that WorkflowConfig and WorkflowContext are removed after workflow got expired. boolean workflowExpired = TestHelper.verify(() -> { WorkflowContext wCtx = _driver.getWorkflowContext(workflowName); WorkflowConfig wCfg = _driver.getWorkflowConfig(workflowName); return (wCtx == null && wCfg == null); }, TestHelper.WAIT_DURATION); Assert.assertTrue(workflowExpired); _controller.syncStop(); // Write workflow context to ZooKeeper _manager.getHelixDataAccessor().getBaseDataAccessor().set(workflowContextPath, record, AccessOption.PERSISTENT); // Verify context is written back to ZK. record = _manager.getHelixDataAccessor().getBaseDataAccessor().get(workflowContextPath, null, AccessOption.PERSISTENT); Assert.assertNotNull(record); // start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // Create and start new workflow just to make sure controller is running and new workflow is // scheduled successfully. String workflowName2 = TestHelper.getTestMethodName() + "_2"; Workflow.Builder builder2 = createSimpleWorkflowBuilder(workflowName2); _driver.start(builder2.build()); _driver.pollForWorkflowState(workflowName2, TaskState.COMPLETED); // Verify that WorkflowContext will be deleted boolean contextDeleted = TestHelper.verify(() -> { WorkflowContext wCtx = _driver.getWorkflowContext(workflowName); return (wCtx == null); }, TestHelper.WAIT_DURATION); Assert.assertTrue(contextDeleted); } @Test public void testJobContextGarbageCollection() throws Exception { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName).setExpiry(1000000L); JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName).setTimeoutPerTask(Long.MAX_VALUE) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); builder.addJob("JOB0", jobBuilder1); _driver.start(builder.build()); // Wait until workflow is COMPLETED _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); JobContext jobContext = accessor.getProperty(accessor.keyBuilder().jobContextZNode(workflowName, "JOB0")); Assert.assertNotNull(jobContext); _controller.syncStop(); // Write workflow context to ZooKeeper jobContext.setName(TaskUtil.getNamespacedJobName(workflowName, "JOB1")); accessor.setProperty(accessor.keyBuilder().jobContextZNode(workflowName, "JOB1"), jobContext); // Verify context is written back to ZK. jobContext = accessor.getProperty(accessor.keyBuilder().jobContextZNode(workflowName, "JOB1")); Assert.assertNotNull(jobContext); // start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // Create and start new workflow just to make sure controller is running and new workflow is // scheduled successfully. String workflowName2 = TestHelper.getTestMethodName() + "_2"; Workflow.Builder builder2 = createSimpleWorkflowBuilder(workflowName2); _driver.start(builder2.build()); _driver.pollForWorkflowState(workflowName2, TaskState.COMPLETED); // Verify that JobContext will be deleted boolean contextDeleted = TestHelper.verify(() -> { JobContext jobCtx = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")); return (jobCtx == null); }, TestHelper.WAIT_DURATION); Assert.assertTrue(contextDeleted); } private Workflow.Builder createSimpleWorkflowBuilder(String workflowName) { final long expiryTime = 5000L; Workflow.Builder builder = new Workflow.Builder(workflowName); // Workflow DAG Schematic: // JOB0 // /\ // / \ // / \ // JOB1 JOB2 JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); JobConfig.Builder jobBuilder3 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); builder.addParentChildDependency("JOB0", "JOB1"); builder.addParentChildDependency("JOB0", "JOB2"); builder.addJob("JOB0", jobBuilder1); builder.addJob("JOB1", jobBuilder2); builder.addJob("JOB2", jobBuilder3); builder.setExpiry(expiryTime); return builder; } }
9,646
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskStopQueue.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.AccessOption; import org.apache.helix.TestHelper; import org.apache.helix.ZkTestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.testng.Assert; import org.testng.annotations.Test; /** * This test makes sure the workflow can be stopped if currentState is deleted. */ public class TestTaskStopQueue extends TaskTestBase { private static final long TIMEOUT = 200000L; private static final String EXECUTION_TIME = "100000"; @Test public void testStopRunningQueue() throws InterruptedException { String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder0 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setTimeoutPerTask(TIMEOUT).setMaxAttemptsPerTask(10).setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, EXECUTION_TIME)); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("JOB0", jobBuilder0); _driver.start(jobQueue.build()); _driver.pollForWorkflowState(jobQueueName, TaskState.IN_PROGRESS); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"), TaskState.IN_PROGRESS); _controller.syncStop(); _driver.stop(jobQueueName); String namespacedJobName = TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"); for (int i = 0; i < _numNodes; i++) { String instance = PARTICIPANT_PREFIX + "_" + (_startPort + i); ZkClient client = (ZkClient) _participants[i].getZkClient(); String sessionId = ZkTestHelper.getSessionId(client); String currentStatePath = "/" + CLUSTER_NAME + "/INSTANCES/" + instance + "/CURRENTSTATES/" + sessionId + "/" + namespacedJobName; _manager.getHelixDataAccessor().getBaseDataAccessor().remove(currentStatePath, AccessOption.PERSISTENT); Assert.assertFalse(_manager.getHelixDataAccessor().getBaseDataAccessor() .exists(currentStatePath, AccessOption.PERSISTENT)); } // Start the Controller String controllerName = CONTROLLER_PREFIX + "_1"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _driver.pollForWorkflowState(jobQueueName, TaskState.STOPPED); _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"), TaskState.STOPPED); } }
9,647
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestExecutionDelay.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test To check if the Execution Delay is respected. */ public class TestExecutionDelay extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); } @Test public void testExecutionDelay() throws Exception { // Execution Delay is set to be a large number. Hence, the workflow should not be completed // soon. final long executionDelay = 100000000000L; String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); // Workflow DAG Schematic: // JOB0 // /\ // / \ // / \ // JOB1 JOB2 JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); JobConfig.Builder jobBuilder3 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); builder.addParentChildDependency("JOB0", "JOB1"); builder.addParentChildDependency("JOB0", "JOB2"); builder.addJob("JOB0", jobBuilder.setExecutionDelay(executionDelay)); builder.addJob("JOB1", jobBuilder2); builder.addJob("JOB2", jobBuilder3); // Since the execution delay is set as a long time, it is expected to reach time out. // If the workflow completed without any exception, it means that ExecutionDelay has not been // respected. _driver.start(builder.build()); // Verify workflow Context is created. // Wait until Workflow Context is created. boolean workflowCreated = TestHelper.verify(() -> { WorkflowContext wCtx1 = _driver.getWorkflowContext(workflowName); return wCtx1 != null; }, 30 * 1000); Assert.assertTrue(workflowCreated); // Verify StartTime is set for the Job0. // Wait until startTime is set. boolean startTimeSet = TestHelper.verify(() -> { WorkflowContext wCtx1 = _driver.getWorkflowContext(workflowName); long startTime = -1; try { startTime = wCtx1.getJobStartTime(TaskUtil.getNamespacedJobName(workflowName, "JOB0")); } catch (Exception e) { // pass } return startTime != -1; }, 30 * 1000); Assert.assertTrue(startTimeSet); // Verify JobContext is not created. Creation of the JobContext means that the job is ran or // in-progress. The absence of JobContext implies that the job did not run. boolean isJobStarted = TestHelper.verify(() -> { JobContext jobCtx0 = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB0")); JobContext jobCtx1 = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")); JobContext jobCtx2 = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB2")); return (jobCtx0 != null || jobCtx1 != null || jobCtx2 != null); }, 30 * 1000); Assert.assertFalse(isJobStarted); WorkflowContext wCtx1 = _driver.getWorkflowContext(workflowName); Assert.assertNull(wCtx1.getJobState(TaskUtil.getNamespacedJobName(workflowName, "JOB0"))); Assert.assertNull(wCtx1.getJobState(TaskUtil.getNamespacedJobName(workflowName, "JOB1"))); Assert.assertNull(wCtx1.getJobState(TaskUtil.getNamespacedJobName(workflowName, "JOB2"))); } }
9,648
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestIndependentTaskRebalancer.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.ScheduleConfig; import org.apache.helix.task.Task; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskResult.Status; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowContext; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Sets; public class TestIndependentTaskRebalancer extends TaskTestBase { private Set<String> _invokedClasses = Sets.newHashSet(); private Map<String, Integer> _runCounts = Maps.newHashMap(); private static final AtomicBoolean _failureCtl = new AtomicBoolean(true); @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < _numNodes; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } // start dummy participants for (int i = 0; i < _numNodes; i++) { final String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); // Set task callbacks Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put("TaskOne", context -> new TaskOne(context, instanceName)); taskFactoryReg.put("TaskTwo", context -> new TaskTwo(context, instanceName)); taskFactoryReg.put("ControllableFailTask", context -> new Task() { @Override public TaskResult run() { if (_failureCtl.get()) { return new TaskResult(Status.FAILED, null); } else { return new TaskResult(Status.COMPLETED, null); } } @Override public void cancel() { } }); taskFactoryReg.put("SingleFailTask", context -> new SingleFailTask()); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } // Start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // Start an admin connection _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _driver = new TaskDriver(_manager); } @BeforeMethod public void beforeMethod() { _invokedClasses.clear(); _runCounts.clear(); } @Test public void testDifferentTasks() throws Exception { // Create a job with two different tasks String jobName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(jobName); List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(2); TaskConfig taskConfig1 = new TaskConfig("TaskOne", null); TaskConfig taskConfig2 = new TaskConfig("TaskTwo", null); taskConfigs.add(taskConfig1); taskConfigs.add(taskConfig2); Map<String, String> jobCommandMap = Maps.newHashMap(); jobCommandMap.put("Timeout", "1000"); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(jobCommandMap); workflowBuilder.addJob(jobName, jobBuilder); _driver.start(workflowBuilder.build()); // Ensure the job completes _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); // Ensure that each class was invoked Assert.assertTrue(_invokedClasses.contains(TaskOne.class.getName())); Assert.assertTrue(_invokedClasses.contains(TaskTwo.class.getName())); } @Test public void testThresholdFailure() throws Exception { // Create a job with two different tasks String jobName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(jobName); List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(2); Map<String, String> taskConfigMap = Maps.newHashMap(ImmutableMap.of("fail", "" + true)); TaskConfig taskConfig1 = new TaskConfig("TaskOne", taskConfigMap); TaskConfig taskConfig2 = new TaskConfig("TaskTwo", null); taskConfigs.add(taskConfig1); taskConfigs.add(taskConfig2); Map<String, String> jobConfigMap = Maps.newHashMap(); jobConfigMap.put("Timeout", "1000"); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .setFailureThreshold(1).addTaskConfigs(taskConfigs).setJobCommandConfigMap(jobConfigMap); workflowBuilder.addJob(jobName, jobBuilder); _driver.start(workflowBuilder.build()); // Ensure the job completes _driver.pollForWorkflowState(jobName, TaskState.IN_PROGRESS); _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); // Ensure that each class was invoked Assert.assertTrue(_invokedClasses.contains(TaskOne.class.getName())); Assert.assertTrue(_invokedClasses.contains(TaskTwo.class.getName())); } @Test public void testReassignment() throws Exception { String workflowName = TestHelper.getTestMethodName(); String jobNameSuffix = "job"; String jobName = String.format("%s_%s", workflowName, jobNameSuffix); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(2); TaskConfig taskConfig1 = new TaskConfig("ControllableFailTask", new HashMap<>()); taskConfigs.add(taskConfig1); Map<String, String> jobCommandMap = Maps.newHashMap(); jobCommandMap.put("Timeout", "1000"); // Retry forever JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand").addTaskConfigs(taskConfigs) .setJobCommandConfigMap(jobCommandMap).setMaxAttemptsPerTask(Integer.MAX_VALUE); workflowBuilder.addJob(jobNameSuffix, jobBuilder); _driver.start(workflowBuilder.build()); // Poll to ensure that the gets re-attempted first int trial = 0; while (trial < 1000) { // 100 sec JobContext jctx = _driver.getJobContext(jobName); if (jctx != null && jctx.getPartitionNumAttempts(0) > 1) { break; } Thread.sleep(100); trial += 1; } if (trial == 1000) { // Fail if no re-attempts Assert.fail("Job " + jobName + " is not retried"); } // Signal the next retry to be successful _failureCtl.set(false); // Verify that retry will go on and the workflow will finally complete _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); } @Test public void testOneTimeScheduled() throws Exception { String jobName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(jobName); List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(1); Map<String, String> taskConfigMap = Maps.newHashMap(); TaskConfig taskConfig1 = new TaskConfig("TaskOne", taskConfigMap); taskConfigs.add(taskConfig1); Map<String, String> jobCommandMap = Maps.newHashMap(); jobCommandMap.put(MockTask.JOB_DELAY, "1000"); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(jobCommandMap); workflowBuilder.addJob(jobName, jobBuilder); long inFiveSeconds = System.currentTimeMillis() + (5 * 1000); workflowBuilder.setScheduleConfig(ScheduleConfig.oneTimeDelayedStart(new Date(inFiveSeconds))); _driver.start(workflowBuilder.build()); // Ensure the job completes _driver.pollForWorkflowState(jobName, TaskState.IN_PROGRESS); _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); // Ensure that the class was invoked Assert.assertTrue(_invokedClasses.contains(TaskOne.class.getName())); // Check that the workflow only started after the start time (with a 1 second buffer) WorkflowContext workflowCtx = _driver.getWorkflowContext(jobName); long startTime = workflowCtx.getStartTime(); Assert.assertTrue(startTime <= inFiveSeconds); } @Test public void testDelayedRetry() throws Exception { // Create a single job with single task, set retry delay int delay = 3000; String jobName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(jobName); List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(1); Map<String, String> taskConfigMap = Maps.newHashMap(); TaskConfig taskConfig1 = new TaskConfig("SingleFailTask", taskConfigMap); taskConfigs.add(taskConfig1); Map<String, String> jobCommandMap = Maps.newHashMap(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .setTaskRetryDelay(delay).addTaskConfigs(taskConfigs).setJobCommandConfigMap(jobCommandMap); workflowBuilder.addJob(jobName, jobBuilder); SingleFailTask.hasFailed = false; _driver.start(workflowBuilder.build()); // Ensure completion _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); // Ensure a single retry happened JobContext jobCtx = _driver.getJobContext(jobName + "_" + jobName); Assert.assertEquals(jobCtx.getPartitionNumAttempts(0), 2); Assert.assertTrue(jobCtx.getFinishTime() - jobCtx.getStartTime() >= delay); } private class TaskOne extends MockTask { private final boolean _shouldFail; private final String _instanceName; TaskOne(TaskCallbackContext context, String instanceName) { super(context); // Check whether or not this task should succeed TaskConfig taskConfig = context.getTaskConfig(); boolean shouldFail = false; if (taskConfig != null) { Map<String, String> configMap = taskConfig.getConfigMap(); if (configMap != null && configMap.containsKey("fail") && Boolean.parseBoolean(configMap.get("fail"))) { // if a specific instance is specified, only fail for that one shouldFail = !configMap.containsKey("failInstance") || configMap.get("failInstance").equals(instanceName); } } _shouldFail = shouldFail; // Initialize the count for this instance if not already done if (!_runCounts.containsKey(instanceName)) { _runCounts.put(instanceName, 0); } _instanceName = instanceName; } @Override public synchronized TaskResult run() { _invokedClasses.add(getClass().getName()); _runCounts.put(_instanceName, _runCounts.get(_instanceName) + 1); // Fail the task if it should fail if (_shouldFail) { return new TaskResult(Status.ERROR, null); } return super.run(); } } private class TaskTwo extends TaskOne { TaskTwo(TaskCallbackContext context, String instanceName) { super(context, instanceName); } } private static class SingleFailTask implements Task { static boolean hasFailed = false; @Override public synchronized TaskResult run() { if (!hasFailed) { hasFailed = true; return new TaskResult(Status.ERROR, null); } return new TaskResult(Status.COMPLETED, null); } @Override public void cancel() { } } }
9,649
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestScheduleDelayTask.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestScheduleDelayTask extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); } @Test public void testScheduleDelayTaskWithDelayTime() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); builder.addParentChildDependency("Job1", "Job4"); builder.addParentChildDependency("Job2", "Job4"); builder.addParentChildDependency("Job3", "Job4"); builder.addJob("Job1", jobBuilder); builder.addJob("Job2", jobBuilder); builder.addJob("Job3", jobBuilder); builder.addJob("Job4", jobBuilder.setExecutionDelay(2000L)); _driver.start(builder.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "Job4"), TaskState.COMPLETED); long jobFinishTime = 0L; for (int i = 1; i <= 3; i++) { jobFinishTime = Math.max(jobFinishTime, _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "Job" + i)) .getFinishTime()); } long jobTwoStartTime = _driver.getWorkflowContext(workflowName) .getJobStartTime(TaskUtil.getNamespacedJobName(workflowName, "Job4")); Assert.assertTrue(jobTwoStartTime - jobFinishTime >= 2000L); } @Test public void testScheduleDelayTaskWithStartTime() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); long currentTime = System.currentTimeMillis(); builder.addParentChildDependency("Job1", "Job2"); builder.addJob("Job1", jobBuilder); builder.addJob("Job2", jobBuilder.setExecutionStart(currentTime + 5000L)); _driver.start(builder.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "Job2"), TaskState.COMPLETED); long jobTwoStartTime = _driver.getWorkflowContext(workflowName) .getJobStartTime(TaskUtil.getNamespacedJobName(workflowName, "Job2")); Assert.assertTrue(jobTwoStartTime - currentTime >= 5000L); } @Test public void testJobQueueDelay() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); JobQueue.Builder queueBuild = TaskTestUtil.buildJobQueue(workflowName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); for (int i = 1; i < 4; i++) { queueBuild.enqueueJob("Job" + i, jobBuilder); } queueBuild.enqueueJob("Job4", jobBuilder.setExecutionDelay(2000L)); _driver.start(queueBuild.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "Job4"), TaskState.COMPLETED); long jobFinishTime = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "Job3")).getFinishTime(); long jobTwoStartTime = _driver.getWorkflowContext(workflowName) .getJobStartTime(TaskUtil.getNamespacedJobName(workflowName, "Job4")); Assert.assertTrue(jobTwoStartTime - jobFinishTime >= 2000L); } @Test public void testDeplayTimeAndStartTime() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); builder.addParentChildDependency("Job1", "Job2"); long currentTime = System.currentTimeMillis(); builder.addJob("Job1", jobBuilder); builder .addJob("Job2", jobBuilder.setExecutionDelay(2000L).setExecutionStart(currentTime + 5000L)); _driver.start(builder.build()); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "Job2"), TaskState.COMPLETED); long jobTwoStartTime = _driver.getWorkflowContext(workflowName) .getJobStartTime(TaskUtil.getNamespacedJobName(workflowName, "Job2")); Assert.assertTrue(jobTwoStartTime - currentTime >= 5000L); } }
9,650
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskCurrentStatePathDisabled.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.HelixDataAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.SystemPropertyKeys; import org.apache.helix.TestHelper; import org.apache.helix.ZkTestHelper; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This test makes sure that the Current State of the task are being removed after participant * handles new session. */ public class TestTaskCurrentStatePathDisabled extends TaskTestBase { private static final String DATABASE = WorkflowGenerator.DEFAULT_TGT_DB; protected HelixDataAccessor _accessor; @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; _numNodes = 1; super.beforeClass(); } @AfterClass public void afterClass() throws Exception { super.afterClass(); System.setProperty(SystemPropertyKeys.TASK_CURRENT_STATE_PATH_DISABLED, "false"); } @Test public void testTaskCurrentStatePathDisabled() throws Exception { String jobQueueName0 = TestHelper.getTestMethodName() + "_0"; JobConfig.Builder jobBuilder0 = new JobConfig.Builder().setWorkflow(jobQueueName0).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobQueue.Builder jobQueue0 = TaskTestUtil.buildJobQueue(jobQueueName0); jobQueue0.enqueueJob("JOB0", jobBuilder0); _driver.start(jobQueue0.build()); String namespacedJobName0 = TaskUtil.getNamespacedJobName(jobQueueName0, "JOB0"); _driver.pollForJobState(jobQueueName0, namespacedJobName0, TaskState.IN_PROGRESS); // Get the current states of Participant0 String instanceP0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); ZkClient clientP0 = (ZkClient) _participants[0].getZkClient(); String sessionIdP0 = ZkTestHelper.getSessionId(clientP0); PropertyKey.Builder keyBuilder = _manager.getHelixDataAccessor().keyBuilder(); Assert.assertTrue(TestHelper.verify(() -> _manager.getHelixDataAccessor() .getProperty(keyBuilder.taskCurrentState(instanceP0, sessionIdP0, namespacedJobName0)) != null, TestHelper.WAIT_DURATION)); Assert.assertNull(_manager.getHelixDataAccessor() .getProperty(keyBuilder.currentState(instanceP0, sessionIdP0, namespacedJobName0))); // Test the case when the task current state path is disabled String jobQueueName1 = TestHelper.getTestMethodName() + "_1"; JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(jobQueueName1).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobQueue.Builder jobQueue1 = TaskTestUtil.buildJobQueue(jobQueueName1); jobQueue1.enqueueJob("JOB1", jobBuilder1); System.setProperty(SystemPropertyKeys.TASK_CURRENT_STATE_PATH_DISABLED, "true"); _driver.start(jobQueue1.build()); String namespacedJobName1 = TaskUtil.getNamespacedJobName(jobQueueName1, "JOB1"); _driver.pollForJobState(jobQueueName1, namespacedJobName1, TaskState.IN_PROGRESS); Assert.assertTrue(TestHelper.verify(() -> _manager.getHelixDataAccessor() .getProperty(keyBuilder.currentState(instanceP0, sessionIdP0, namespacedJobName1)) != null, TestHelper.WAIT_DURATION)); Assert.assertNull(_manager.getHelixDataAccessor() .getProperty(keyBuilder.taskCurrentState(instanceP0, sessionIdP0, namespacedJobName1))); } }
9,651
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskCurrentStateNull.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Map; import org.apache.helix.AccessOption; import org.apache.helix.HelixDataAccessor; import org.apache.helix.TestHelper; import org.apache.helix.ZkTestHelper; import org.apache.helix.model.CurrentState; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; /** * This test makes sure that controller will not be blocked if there exists null current states. */ public class TestTaskCurrentStateNull extends TaskTestBase { protected HelixDataAccessor _accessor; @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; _numNodes = 1; super.beforeClass(); } @AfterClass() public void afterClass() throws Exception { super.afterClass(); } @Test public void testCurrentStateNull() throws Exception { String workflowName1 = TestHelper.getTestMethodName() + "_1"; String workflowName2 = TestHelper.getTestMethodName() + "_2"; Workflow.Builder builder1 = new Workflow.Builder(workflowName1); Workflow.Builder builder2 = new Workflow.Builder(workflowName2); JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName1) .setNumberOfTasks(5).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")); JobConfig.Builder jobBuilder2 = new JobConfig.Builder().setWorkflow(workflowName2) .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")); builder1.addJob("JOB0", jobBuilder1); builder2.addJob("JOB0", jobBuilder2); _driver.start(builder1.build()); _driver.start(builder2.build()); String namespacedJobName1 = TaskUtil.getNamespacedJobName(workflowName1, "JOB0"); String namespacedJobName2 = TaskUtil.getNamespacedJobName(workflowName2, "JOB0"); _driver.pollForJobState(workflowName1, namespacedJobName1, TaskState.IN_PROGRESS); _driver.pollForJobState(workflowName2, namespacedJobName2, TaskState.IN_PROGRESS); // Get the current states of Participant0 String instanceP0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); ZkClient clientP0 = (ZkClient) _participants[0].getZkClient(); String sessionIdP0 = ZkTestHelper.getSessionId(clientP0); String jobCurrentStatePath1 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP0, sessionIdP0, namespacedJobName1).toString(); String jobCurrentStatePath2 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP0, sessionIdP0, namespacedJobName2).toString(); // Read the current states of Participant0 and make sure they have been created boolean isCurrentStateCreated = TestHelper.verify(() -> { ZNRecord recordJob1 = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(jobCurrentStatePath1, new Stat(), AccessOption.PERSISTENT); ZNRecord recordJob2 = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(jobCurrentStatePath2, new Stat(), AccessOption.PERSISTENT); Map<String, String> taskCurrentState = null; if (recordJob2 != null){ taskCurrentState = recordJob2.getMapField(namespacedJobName2 + "_0"); } return (recordJob1 != null && recordJob2 != null && taskCurrentState != null); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isCurrentStateCreated); ZNRecord recordTask = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(jobCurrentStatePath2, new Stat(), AccessOption.PERSISTENT); Map<String, String> taskCurrentState = recordTask.getMapField(namespacedJobName2 + "_0"); taskCurrentState.put(CurrentState.CurrentStateProperty.CURRENT_STATE.name(), null); recordTask.setMapField(namespacedJobName2 + "_0", taskCurrentState); _manager.getHelixDataAccessor().getBaseDataAccessor().set(jobCurrentStatePath2, recordTask, AccessOption.PERSISTENT); _driver.pollForWorkflowState(workflowName1, TestHelper.WAIT_DURATION, TaskState.COMPLETED); } }
9,652
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskNumAttempts.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * TestTaskNumAttempts tests that number of attempts for tasks are incremented correctly respecting * the retry delay. * NOTE: This test relies heavily upon timing. */ public class TestTaskNumAttempts extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; super.beforeClass(); } @Test public void testTaskNumAttemptsWithDelay() throws Exception { int maxAttempts = Integer.MAX_VALUE; // Allow the count to increase infinitely // Use a delay that's long enough for multiple rounds of pipeline long retryDelay = 4000L; String workflowName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG) .setMaxAttemptsPerTask(maxAttempts).setCommand(MockTask.TASK_COMMAND) .setWorkflow(workflowName).setFailureThreshold(Integer.MAX_VALUE) .setTaskRetryDelay(retryDelay).setJobCommandConfigMap( ImmutableMap.of(MockTask.FAILURE_COUNT_BEFORE_SUCCESS, String.valueOf(maxAttempts))); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(workflowName, jobBuilder).build(); _driver.start(flow); // Wait until the job is running _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, workflowName)); int expectedAttempts = jobContext.getPartitionNumAttempts(0); // Check 3 times to see if maxAttempts match up for (int i = 0; i < 3; i++) { // Add a small delay to make sure the check falls in the middle of the scheduling timeline Thread.sleep(retryDelay + 1000L); JobContext ctx = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, workflowName)); expectedAttempts++; Assert.assertEquals(ctx.getPartitionNumAttempts(0), expectedAttempts); } } }
9,653
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskAssignmentCalculator.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.collections.Sets; /** * This class tests basic job and test assignment/scheduling functionality of * TaskAssignmentCalculators. */ public class TestTaskAssignmentCalculator extends TaskTestBase { private Set<String> _invokedClasses = Sets.newHashSet(); private Map<String, Integer> _runCounts = new ConcurrentHashMap<>(); private Map<String, String> _jobCommandMap; private boolean failTask; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; // Setup cluster and instances _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < _numNodes; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } // start dummy participants for (int i = 0; i < _numNodes; i++) { final String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); // Set task callbacks Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put("TaskOne", context -> new TaskOne(context, instanceName)); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } // Start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // Start an admin connection _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _driver = new TaskDriver(_manager); _jobCommandMap = Maps.newHashMap(); } /** * This test does NOT allow multiple jobs being assigned to an instance. * @throws InterruptedException */ @Test public void testMultipleJobAssignment() throws InterruptedException { _runCounts.clear(); failTask = false; String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); for (int i = 0; i < 20; i++) { List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(1); taskConfigs.add(new TaskConfig("TaskOne", new HashMap<>())); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(_jobCommandMap); workflowBuilder.addJob("JOB" + i, jobBuilder); } _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); Assert.assertEquals(_runCounts.size(), 5); } /** * This test explicitly allows overlap job assignment. * @throws InterruptedException */ @Test // This test does NOT allow multiple jobs being assigned to an instance. public void testMultipleJobAssignmentOverlapEnabled() throws InterruptedException { _runCounts.clear(); failTask = false; String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(true); workflowBuilder.setWorkflowConfig(configBuilder.build()); for (int i = 0; i < 40; i++) { List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(1); taskConfigs.add(new TaskConfig("TaskOne", new HashMap<>())); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(_jobCommandMap); workflowBuilder.addJob("JOB" + i, jobBuilder); } _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); Assert.assertEquals(_runCounts.size(), 5); } @Test public void testMultipleTaskAssignment() throws InterruptedException { _runCounts.clear(); failTask = false; String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(20); for (int i = 0; i < 20; i++) { Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigs.add(new TaskConfig("TaskOne", taskConfigMap)); } JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .setJobCommandConfigMap(_jobCommandMap).addTaskConfigs(taskConfigs); workflowBuilder.addJob("JOB", jobBuilder); _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); Assert.assertEquals(_runCounts.size(), 5); } @Test public void testAbortTaskForWorkflowFail() throws InterruptedException { failTask = true; String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); for (int i = 0; i < 5; i++) { List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(1); Map<String, String> taskConfigMap = Maps.newHashMap(); taskConfigs.add(new TaskConfig("TaskOne", taskConfigMap)); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(_jobCommandMap); workflowBuilder.addJob("JOB" + i, jobBuilder); } _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); int abortedTask = 0; for (TaskState jobState : _driver.getWorkflowContext(workflowName).getJobStates().values()) { if (jobState == TaskState.ABORTED) { abortedTask++; } } Assert.assertEquals(abortedTask, 4); } private class TaskOne extends MockTask { private final String _instanceName; TaskOne(TaskCallbackContext context, String instanceName) { super(context); // Initialize the count for this instance if not already done if (!_runCounts.containsKey(instanceName)) { _runCounts.put(instanceName, 0); } _instanceName = instanceName; } @Override public TaskResult run() { _invokedClasses.add(getClass().getName()); _runCounts.put(_instanceName, _runCounts.get(_instanceName) + 1); if (failTask) { return new TaskResult(TaskResult.Status.FAILED, ""); } return new TaskResult(TaskResult.Status.COMPLETED, ""); } } }
9,654
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskThrottling.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.HelixConfigScope; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.builder.HelixConfigScopeBuilder; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestTaskThrottling extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); _numNodes = 2; super.beforeClass(); } /** * This test has been disabled/deprecated because Task Framework 2.0 uses quotas that are meant to * throttle tasks. * @throws InterruptedException */ @Test public void testTaskThrottle() throws Exception { int numTasks = 30 * _numNodes; // 60 tasks int perNodeTaskLimitation = 5; JobConfig.Builder jobConfig = generateLongRunJobConfig(numTasks); // 1. Job executed in the participants with no limitation String jobName1 = "Job1"; Workflow flow1 = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName1, jobConfig).build(); _driver.start(flow1); _driver.pollForJobState(flow1.getName(), TaskUtil.getNamespacedJobName(flow1.getName(), jobName1), TaskState.IN_PROGRESS); Assert.assertTrue(TestHelper.verify(() -> (countRunningPartition(flow1, jobName1) == numTasks), TestHelper.WAIT_DURATION)); _driver.stop(flow1.getName()); _driver.pollForWorkflowState(flow1.getName(), TaskState.STOPPED); // 2. Job executed in the participants with max task limitation // Configuring cluster HelixConfigScope scope = new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.CLUSTER) .forCluster(CLUSTER_NAME).build(); Map<String, String> properties = new HashMap<>(); properties.put(ClusterConfig.ClusterConfigProperty.MAX_CONCURRENT_TASK_PER_INSTANCE.name(), Integer.toString(perNodeTaskLimitation)); _gSetupTool.getClusterManagementTool().setConfig(scope, properties); String jobName2 = "Job2"; Workflow flow2 = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName2, jobConfig).build(); _driver.start(flow2); _driver.pollForJobState(flow2.getName(), TaskUtil.getNamespacedJobName(flow2.getName(), jobName2), TaskState.IN_PROGRESS); // Expect 10 tasks Assert.assertTrue(TestHelper.verify( () -> (countRunningPartition(flow2, jobName2) == (_numNodes * perNodeTaskLimitation)), TestHelper.WAIT_DURATION)); _driver.stop(flow2.getName()); _driver.pollForWorkflowState(flow2.getName(), TaskState.STOPPED); // 3. Ensure job can finish normally jobConfig.setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10")); String jobName3 = "Job3"; Workflow flow3 = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName3, jobConfig).build(); _driver.start(flow3); _driver.pollForJobState(flow3.getName(), TaskUtil.getNamespacedJobName(flow3.getName(), jobName3), TaskState.COMPLETED); } // Disable this test since helix will have priority map when integrate with JobIterator. @Test(dependsOnMethods = { "testTaskThrottle" }, enabled = false) public void testJobPriority() throws Exception { int numTasks = 30 * _numNodes; int perNodeTaskLimitation = 5; JobConfig.Builder jobConfig = generateLongRunJobConfig(numTasks); // Configuring participants setParticipantsCapacity(perNodeTaskLimitation); // schedule job1 String jobName1 = "PriorityJob1"; Workflow flow1 = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName1, jobConfig).build(); _driver.start(flow1); _driver.pollForJobState(flow1.getName(), TaskUtil.getNamespacedJobName(flow1.getName(), jobName1), TaskState.IN_PROGRESS); Assert.assertTrue(TestHelper.verify( () -> (countRunningPartition(flow1, jobName1) == (_numNodes * perNodeTaskLimitation)), TestHelper.WAIT_DURATION)); // schedule job2 String jobName2 = "PriorityJob2"; Workflow flow2 = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName2, jobConfig).build(); _driver.start(flow2); _driver.pollForJobState(flow2.getName(), TaskUtil.getNamespacedJobName(flow2.getName(), jobName2), TaskState.IN_PROGRESS); Assert.assertTrue(TestHelper.verify(() -> (countRunningPartition(flow2, jobName2) == 0), TestHelper.WAIT_DURATION)); // Increasing participants capacity setParticipantsCapacity(2 * perNodeTaskLimitation); // Additional capacity should all be used by job1 Assert.assertTrue(TestHelper.verify( () -> (countRunningPartition(flow1, jobName1) == (_numNodes * 2 * perNodeTaskLimitation)), TestHelper.WAIT_DURATION)); Assert.assertTrue(TestHelper.verify(() -> (countRunningPartition(flow2, jobName2) == 0), TestHelper.WAIT_DURATION)); _driver.stop(flow1.getName()); _driver.pollForWorkflowState(flow1.getName(), TaskState.STOPPED); _driver.stop(flow2.getName()); _driver.pollForWorkflowState(flow2.getName(), TaskState.STOPPED); } private int countRunningPartition(Workflow flow, String jobName) { int runningPartition = 0; JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(flow.getName(), jobName)); for (int partition : jobContext.getPartitionSet()) { if (jobContext.getPartitionState(partition) != null && jobContext.getPartitionState(partition).equals(TaskPartitionState.RUNNING)) { runningPartition++; } } return runningPartition; } private JobConfig.Builder generateLongRunJobConfig(int numTasks) { JobConfig.Builder jobConfig = new JobConfig.Builder(); List<TaskConfig> taskConfigs = new ArrayList<>(); for (int j = 0; j < numTasks; j++) { taskConfigs.add(new TaskConfig.Builder().setTaskId("task_" + j) .setCommand(MockTask.TASK_COMMAND).build()); } jobConfig.addTaskConfigs(taskConfigs).setNumConcurrentTasksPerInstance(numTasks) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "120000")); return jobConfig; } private void setParticipantsCapacity(int perNodeTaskLimitation) { for (int i = 0; i < _numNodes; i++) { InstanceConfig instanceConfig = _gSetupTool.getClusterManagementTool() .getInstanceConfig(CLUSTER_NAME, PARTICIPANT_PREFIX + "_" + (_startPort + i)); instanceConfig.setMaxConcurrentTask(perNodeTaskLimitation); _gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, PARTICIPANT_PREFIX + "_" + (_startPort + i), instanceConfig); } } }
9,655
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskAssignment.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestTaskAssignment extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); _numNodes = 2; _instanceGroupTag = true; super.beforeClass(); } @Test public void testTaskAssignment() throws InterruptedException { _gSetupTool.getClusterManagementTool() .enableInstance(CLUSTER_NAME, PARTICIPANT_PREFIX + "_" + (_startPort + 0), false); String jobResource = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobResource, jobBuilder).build(); _driver.start(flow); // Wait 1 sec. The task should not be complete since it is not assigned. Thread.sleep(1000L); // The task is not assigned so the task state should be null in this case. Assert.assertNull( _driver.getJobContext(TaskUtil.getNamespacedJobName(jobResource)).getPartitionState(0)); } @Test public void testGenericTaskInstanceGroup() throws InterruptedException { // Disable the only instance can be assigned. String queueName = TestHelper.getTestMethodName(); String jobName = "Job4InstanceGroup"; JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName); JobConfig.Builder jobConfig = new JobConfig.Builder(); List<TaskConfig> taskConfigs = new ArrayList<TaskConfig>(); int num_tasks = 3; for (int j = 0; j < num_tasks; j++) { taskConfigs.add( new TaskConfig.Builder().setTaskId("task_" + j).setCommand(MockTask.TASK_COMMAND) .build()); } jobConfig.addTaskConfigs(taskConfigs); jobConfig.setInstanceGroupTag("TESTTAG1"); queueBuilder.enqueueJob(jobName, jobConfig); _driver.start(queueBuilder.build()); // Wait 1 sec. The task should not be complete since it is not assigned. Thread.sleep(1000L); // The task is not assigned so the task state should be null in this case. String namedSpaceJob = TaskUtil.getNamespacedJobName(queueName, jobName); Assert.assertEquals(_driver.getJobContext(namedSpaceJob).getAssignedParticipant(0), _participants[1].getInstanceName()); } }
9,656
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestStopWorkflow.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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 com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestStopWorkflow extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; super.beforeClass(); } @Test public void testStopWorkflow() throws InterruptedException { stopTestSetup(5); String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG).setWorkflow(jobQueueName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.SUCCESS_COUNT_BEFORE_FAIL, "1")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("job1_will_succeed", jobBuilder); jobQueue.enqueueJob("job2_will_fail", jobBuilder); _driver.start(jobQueue.build()); // job1 should succeed and job2 should fail, wait until that happens _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job2_will_fail"), TaskState.FAILED); Assert.assertEquals(TaskState.IN_PROGRESS, _driver.getWorkflowContext(jobQueueName).getWorkflowState()); // Now stop the workflow, and it should be stopped because all jobs have completed or failed. _driver.waitToStop(jobQueueName, 4000); _driver.pollForWorkflowState(jobQueueName, TaskState.STOPPED); Assert.assertEquals(TaskState.STOPPED, _driver.getWorkflowContext(jobQueueName).getWorkflowState()); cleanupParticipants(5); } /** * Tests that stopping a workflow does result in its task ending up in STOPPED state. * @throws InterruptedException */ @Test(dependsOnMethods = "testStopWorkflow") public void testStopTask() throws Exception { stopTestSetup(1); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName); WorkflowConfig.Builder configBuilder = new WorkflowConfig.Builder(workflowName); configBuilder.setAllowOverlapJobAssignment(true); workflowBuilder.setWorkflowConfig(configBuilder.build()); for (int i = 0; i < 1; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("StopTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand("Dummy") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(new HashMap<>()); workflowBuilder.addJob("JOB" + i, jobConfigBulider); } _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); // Stop the workflow _driver.stop(workflowName); _driver.pollForWorkflowState(workflowName, TaskState.STOPPED); Assert.assertEquals(TaskDriver.getWorkflowContext(_manager, workflowName).getWorkflowState(), TaskState.STOPPED); cleanupParticipants(1); } /** * Tests that stop() indeed frees up quotas for tasks belonging to the stopped workflow. * @throws InterruptedException */ @Test(dependsOnMethods = "testStopTask") public void testStopTaskForQuota() throws Exception { stopTestSetup(1); String workflowNameToStop = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilderToStop = new Workflow.Builder(workflowNameToStop); WorkflowConfig.Builder configBuilderToStop = new WorkflowConfig.Builder(workflowNameToStop); configBuilderToStop.setAllowOverlapJobAssignment(true); workflowBuilderToStop.setWorkflowConfig(configBuilderToStop.build()); // First create 50 jobs so that all 40 threads will be taken up for (int i = 0; i < 50; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("StopTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand("Dummy") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(new HashMap<>()); workflowBuilderToStop.addJob("JOB" + i, jobConfigBulider); } _driver.start(workflowBuilderToStop.build()); _driver.pollForWorkflowState(workflowNameToStop, TaskState.IN_PROGRESS); // Stop the workflow _driver.stop(workflowNameToStop); _driver.pollForWorkflowState(workflowNameToStop, TaskState.STOPPED); Assert.assertEquals( TaskDriver.getWorkflowContext(_manager, workflowNameToStop).getWorkflowState(), TaskState.STOPPED); // Check that the workflow has been stopped // Generate another workflow to be completed this time around String workflowToComplete = TestHelper.getTestMethodName() + "ToComplete"; Workflow.Builder workflowBuilderToComplete = new Workflow.Builder(workflowToComplete); WorkflowConfig.Builder configBuilderToComplete = new WorkflowConfig.Builder(workflowToComplete); configBuilderToComplete.setAllowOverlapJobAssignment(true); workflowBuilderToComplete.setWorkflowConfig(configBuilderToComplete.build()); // Create 20 jobs that should complete for (int i = 0; i < 20; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("CompleteTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand("Dummy") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(new HashMap<>()); workflowBuilderToComplete.addJob("JOB" + i, jobConfigBulider); } // Start the workflow to be completed _driver.start(workflowBuilderToComplete.build()); _driver.pollForWorkflowState(workflowToComplete, TaskState.COMPLETED); Assert.assertEquals( TaskDriver.getWorkflowContext(_manager, workflowToComplete).getWorkflowState(), TaskState.COMPLETED); cleanupParticipants(1); } /** * Test that there is no thread leak when stopping and resuming. * @throws InterruptedException */ @Test(dependsOnMethods = "testStopTaskForQuota") public void testResumeTaskForQuota() throws Exception { stopTestSetup(1); String workflowName_1 = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder_1 = new Workflow.Builder(workflowName_1); WorkflowConfig.Builder configBuilder_1 = new WorkflowConfig.Builder(workflowName_1); configBuilder_1.setAllowOverlapJobAssignment(true); workflowBuilder_1.setWorkflowConfig(configBuilder_1.build()); // 30 jobs run first for (int i = 0; i < 30; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("StopTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand("Dummy") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(new HashMap<>()); workflowBuilder_1.addJob("JOB" + i, jobConfigBulider); } _driver.start(workflowBuilder_1.build()); // Check the jobs are in progress and the tasks are running. // Each job has one task. Hence, we just check the state of the partition 0. for (int i = 0; i < 30; i++) { String jobName = workflowName_1 + "_JOB" + i; _driver.pollForJobState(workflowName_1, jobName, TaskState.IN_PROGRESS); boolean isTaskInRunningState = TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(jobName); String state = jobContext.getMapField(0).get("STATE"); return (state!= null && state.equals("RUNNING")); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isTaskInRunningState); } _driver.stop(workflowName_1); _driver.pollForWorkflowState(workflowName_1, TaskState.STOPPED); _driver.resume(workflowName_1); // Check the jobs are in progress and the tasks are running. // Each job has one task. Hence, we just check the state of the partition 0. for (int i = 0; i < 30; i++) { String jobName = workflowName_1 + "_JOB" + i; _driver.pollForJobState(workflowName_1, jobName, TaskState.IN_PROGRESS); boolean isTaskInRunningState = TestHelper.verify(() -> { JobContext jobContext = _driver.getJobContext(jobName); String state = jobContext.getMapField(0).get("STATE"); return (state!= null && state.equals("RUNNING")); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isTaskInRunningState); } // By now there should only be 30 threads occupied String workflowName_2 = TestHelper.getTestMethodName() + "_2"; Workflow.Builder workflowBuilder_2 = new Workflow.Builder(workflowName_2); WorkflowConfig.Builder configBuilder_2 = new WorkflowConfig.Builder(workflowName_2); configBuilder_2.setAllowOverlapJobAssignment(true); workflowBuilder_2.setWorkflowConfig(configBuilder_2.build()); // Try to run 10 jobs that complete int numJobs = 10; for (int i = 0; i < numJobs; i++) { List<TaskConfig> taskConfigs = new ArrayList<>(); taskConfigs.add(new TaskConfig("CompleteTask", new HashMap<>())); JobConfig.Builder jobConfigBulider = new JobConfig.Builder().setCommand("Dummy") .addTaskConfigs(taskConfigs).setJobCommandConfigMap(new HashMap<>()); workflowBuilder_2.addJob("JOB" + i, jobConfigBulider); } // If these jobs complete successfully, then that means there is no thread leak _driver.start(workflowBuilder_2.build()); Assert.assertEquals(_driver.pollForWorkflowState(workflowName_2, TaskState.COMPLETED), TaskState.COMPLETED); cleanupParticipants(1); } /** * Sets up an environment to make stop task testing easy. Shuts down all Participants and starts * only one Participant. */ private void stopTestSetup(int numNodes) { // Set task callbacks Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); TaskFactory taskFactory = StopTask::new; TaskFactory taskFactoryComplete = MockTask::new; taskFactoryReg.put("StopTask", taskFactory); taskFactoryReg.put("CompleteTask", taskFactoryComplete); stopParticipants(); for (int i = 0; i < numNodes; i++) { String instanceName = _participants[i].getInstanceName(); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } } private void cleanupParticipants(int numNodes) { for (int i = 0; i < numNodes; i++) { if (_participants[i] != null && _participants[i].isConnected()) { _participants[i].syncStop(); } } } /** * A mock task class that models a short-lived task to be stopped. */ private class StopTask extends MockTask { private boolean _stopFlag = false; StopTask(TaskCallbackContext context) { super(context); } @Override public TaskResult run() { _stopFlag = false; while (!_stopFlag) { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } // This wait is to prevent the task from completing before being stopped try { Thread.sleep(500L); } catch (InterruptedException e) { e.printStackTrace(); } return new TaskResult(TaskResult.Status.CANCELED, ""); } @Override public void cancel() { _stopFlag = true; } } }
9,657
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestWorkflowTimeout.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Collections; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestWorkflowTimeout extends TaskTestBase { private final static String JOB_NAME = "TestJob"; private JobConfig.Builder _jobBuilder; @BeforeClass public void beforeClass() throws Exception { _numDbs = 1; _numNodes = 3; _numPartitions = 5; _numReplicas = 3; super.beforeClass(); // Create a non-stop job _jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); } @Test public void testWorkflowRunningTime() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); _jobBuilder.setWorkflow(workflowName); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName) .setWorkflowConfig(new WorkflowConfig.Builder(workflowName).setTimeout(1000).build()) .addJob(JOB_NAME, _jobBuilder); _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(workflowName, 10000L, TaskState.TIMED_OUT); } @Test public void testWorkflowPausedTimeout() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); _jobBuilder.setWorkflow(workflowName); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName) .setWorkflowConfig(new WorkflowConfig.Builder(workflowName).setTimeout(5000).build()) .addJob(JOB_NAME, _jobBuilder); _driver.start(workflowBuilder.build()); // Pause the queue _driver.waitToStop(workflowName, 10000L); _driver.pollForWorkflowState(workflowName, 10000L, TaskState.TIMED_OUT); } @Test public void testJobQueueNotApplyTimeout() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); // Make jobs run success _jobBuilder.setWorkflow(queueName).setJobCommandConfigMap(Collections.EMPTY_MAP); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(queueName); jobQueue.setWorkflowConfig(new WorkflowConfig.Builder(queueName).setTimeout(1000).build()) .enqueueJob(JOB_NAME, _jobBuilder).enqueueJob(JOB_NAME + 1, _jobBuilder); _driver.start(jobQueue.build()); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, JOB_NAME), TaskState.COMPLETED); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, JOB_NAME + 1), TaskState.COMPLETED); // Add back the config _jobBuilder.setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")); } @Test public void testWorkflowTimeoutWhenWorkflowCompleted() throws Exception { String workflowName = TestHelper.getTestMethodName(); long expiry = 2000L; _jobBuilder.setWorkflow(workflowName); _jobBuilder.setJobCommandConfigMap(Collections.<String, String> emptyMap()); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName) .setWorkflowConfig(new WorkflowConfig.Builder(workflowName).setTimeout(0).build()) .addJob(JOB_NAME, _jobBuilder).setExpiry(expiry); // Since workflow's Timeout is 0, the workflow goes to TIMED_OUT state right away long startTime = System.currentTimeMillis(); _driver.start(workflowBuilder.build()); Assert.assertTrue(TestHelper.verify(() -> (_driver.getWorkflowConfig(workflowName) == null && _driver.getWorkflowContext(workflowName) == null), TestHelper.WAIT_DURATION)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - startTime >= expiry); } }
9,658
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskSchedulingTwoCurrentStates.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.apache.helix.AccessOption; import org.apache.helix.HelixDataAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.ZkTestHelper; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.CurrentState; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskUtil; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; /** * Test to check if targeted tasks correctly get assigned and also if cancel messages are not being * sent when there are two CurrentStates. */ public class TestTaskSchedulingTwoCurrentStates extends TaskTestBase { private static final String DATABASE = "TestDB_" + TestHelper.getTestClassName(); protected HelixDataAccessor _accessor; private PropertyKey.Builder _keyBuilder; private static final AtomicInteger CANCEL_COUNT = new AtomicInteger(0); @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; _numNodes = 3; super.beforeClass(); // Stop participants that have been started in super class for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); Assert.assertFalse(_participants[i].isConnected()); } // Start new participants that have new TaskStateModel (NewMockTask) information _participants = new MockParticipantManager[_numNodes]; for (int i = 0; i < _numNodes; i++) { Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(NewMockTask.TASK_COMMAND, NewMockTask::new); String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } } @AfterClass() public void afterClass() throws Exception { super.afterClass(); } @Test public void testTargetedTaskTwoCurrentStates() throws Exception { _gSetupTool.addResourceToCluster(CLUSTER_NAME, DATABASE, _numPartitions, MASTER_SLAVE_STATE_MODEL, IdealState.RebalanceMode.SEMI_AUTO.name()); _gSetupTool.rebalanceResource(CLUSTER_NAME, DATABASE, 3); List<String> preferenceList = new ArrayList<>(); preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 1)); preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 0)); preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 2)); IdealState idealState = new IdealState(DATABASE); idealState.setPreferenceList(DATABASE + "_0", preferenceList); _gSetupTool.getClusterManagementTool().updateIdealState(CLUSTER_NAME, DATABASE, idealState); // [Participant0: localhost_12918, Participant1: localhost_12919, Participant2: localhost_12920] // Preference list [localhost_12919, localhost_12918, localhost_12920] // Status: [Participant1: Master, Participant0: Slave, Participant2: Slave] // Based on the above preference list and since is is SEMI_AUTO, localhost_12919 will be Master. String jobQueueName = TestHelper.getTestMethodName(); JobConfig.Builder jobBuilder0 = new JobConfig.Builder().setWorkflow(jobQueueName).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("JOB0", jobBuilder0); // Make sure master has been correctly switched to Participant1 boolean isMasterSwitchedToCorrectInstance = TestHelper.verify(() -> { ExternalView externalView = _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, DATABASE); if (externalView == null) { return false; } Map<String, String> stateMap = externalView.getStateMap(DATABASE + "_0"); if (stateMap == null) { return false; } return "MASTER".equals(stateMap.get(PARTICIPANT_PREFIX + "_" + (_startPort + 1))); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isMasterSwitchedToCorrectInstance); _driver.start(jobQueue.build()); String namespacedJobName = TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"); _driver.pollForJobState(jobQueueName, namespacedJobName, TaskState.IN_PROGRESS); // Task should be assigned to Master -> Participant0 boolean isTaskAssignedToMasterNode = TestHelper.verify(() -> { JobContext ctx = _driver.getJobContext(namespacedJobName); String participant = ctx.getAssignedParticipant(0); if (participant == null) { return false; } return (participant.equals(PARTICIPANT_PREFIX + "_" + (_startPort + 1))); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isTaskAssignedToMasterNode); String instanceP0 = PARTICIPANT_PREFIX + "_" + (_startPort + 0); ZkClient clientP0 = (ZkClient) _participants[0].getZkClient(); String sessionIdP0 = ZkTestHelper.getSessionId(clientP0); String currentStatePathP0 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP0, sessionIdP0, namespacedJobName).toString(); // Get the current state of Participant1 String instanceP1 = PARTICIPANT_PREFIX + "_" + (_startPort + 1); ZkClient clientP1 = (ZkClient) _participants[1].getZkClient(); String sessionIdP1 = ZkTestHelper.getSessionId(clientP1); String currentStatePathP1 = _manager.getHelixDataAccessor().keyBuilder() .taskCurrentState(instanceP1, sessionIdP1, namespacedJobName).toString(); boolean isCurrentStateCreated = TestHelper.verify(() -> { ZNRecord record = _manager.getHelixDataAccessor().getBaseDataAccessor() .get(currentStatePathP1, new Stat(), AccessOption.PERSISTENT); if (record != null) { record.setSimpleField(CurrentState.CurrentStateProperty.SESSION_ID.name(), sessionIdP0); _manager.getHelixDataAccessor().getBaseDataAccessor().set(currentStatePathP0, record, AccessOption.PERSISTENT); return true; } else { return false; } }, TestHelper.WAIT_DURATION); Assert.assertTrue(isCurrentStateCreated); // Wait until the job is finished. _driver.pollForJobState(jobQueueName, namespacedJobName, TaskState.COMPLETED); Assert.assertEquals(CANCEL_COUNT.get(), 0); } /** * A mock task that extents MockTask class to count the number of cancel messages. */ private class NewMockTask extends MockTask { NewMockTask(TaskCallbackContext context) { super(context); } @Override public void cancel() { // Increment the cancel count so we know cancel() has been called CANCEL_COUNT.incrementAndGet(); super.cancel(); } } }
9,659
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestMaxNumberOfAttemptsMasterSwitch.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.helix.HelixDataAccessor; import org.apache.helix.TestHelper; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; /** * Test to check is maximum number of attempts being respected while target partition is switching * continuously. */ public class TestMaxNumberOfAttemptsMasterSwitch extends TaskTestBase { private static final String DATABASE = WorkflowGenerator.DEFAULT_TGT_DB; protected HelixDataAccessor _accessor; private List<String> _assignmentList1; private List<String> _assignmentList2; @BeforeClass public void beforeClass() throws Exception { _numPartitions = 1; _numNodes = 3; super.beforeClass(); _driver = new TaskDriver(_manager); // Assignment1: localhost_12918: Master, localhost_12919:Slave, localhost_12920: Slave _assignmentList1 = new ArrayList<>(); _assignmentList1.add(PARTICIPANT_PREFIX + "_" + (_startPort + 0)); _assignmentList1.add(PARTICIPANT_PREFIX + "_" + (_startPort + 1)); _assignmentList1.add(PARTICIPANT_PREFIX + "_" + (_startPort + 2)); // Assignment2: localhost_12919: Master, localhost_12918:Slave, localhost_12920: Slave _assignmentList2 = new ArrayList<>(); _assignmentList2.add(PARTICIPANT_PREFIX + "_" + (_startPort + 1)); _assignmentList2.add(PARTICIPANT_PREFIX + "_" + (_startPort + 0)); _assignmentList2.add(PARTICIPANT_PREFIX + "_" + (_startPort + 2)); } @AfterClass public void afterClass() throws Exception { super.afterClass(); } @Test public void testMaxNumberOfAttemptsMasterSwitch() throws Exception { String jobQueueName = TestHelper.getTestMethodName(); int maxNumberOfAttempts = 5; assignCustomizedIdealState(_assignmentList1); JobConfig.Builder jobBuilder0 = new JobConfig.Builder().setWorkflow(jobQueueName).setTargetResource(DATABASE) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(maxNumberOfAttempts) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName); jobQueue.enqueueJob("JOB0", jobBuilder0); String nameSpacedJobName = TaskUtil.getNamespacedJobName(jobQueueName, "JOB0"); _driver.start(jobQueue.build()); _driver.pollForJobState(jobQueueName, nameSpacedJobName, TaskState.IN_PROGRESS); boolean isAssignmentInIdealState = true; // Turn on and off the instance (10 times) and make sure task gets retried and number of // attempts gets incremented every time. // Also make sure that the task won't be retried more than maxNumberOfAttempts for (int i = 1; i <= 2 * maxNumberOfAttempts; i++) { int expectedRetryNumber = Math.min(i, maxNumberOfAttempts); Assert .assertTrue( TestHelper.verify( () -> (_driver.getJobContext(nameSpacedJobName) .getPartitionNumAttempts(0) == expectedRetryNumber), TestHelper.WAIT_DURATION)); if (isAssignmentInIdealState) { assignCustomizedIdealState(_assignmentList2); verifyMastership(_assignmentList2); isAssignmentInIdealState = false; } else { assignCustomizedIdealState(_assignmentList1); verifyMastership(_assignmentList1); isAssignmentInIdealState = true; } } // Since the task reaches max number of attempts, ths job will fails. _driver.pollForJobState(jobQueueName, nameSpacedJobName, TaskState.FAILED); Assert.assertEquals(_driver.getJobContext(nameSpacedJobName).getPartitionNumAttempts(0), maxNumberOfAttempts); } private void assignCustomizedIdealState(List<String> _assignmentList) { IdealState idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, DATABASE); idealState.setPartitionState(DATABASE + "_0", _assignmentList.get(0), "MASTER"); idealState.setPartitionState(DATABASE + "_0", _assignmentList.get(1), "SLAVE"); idealState.setPartitionState(DATABASE + "_0", _assignmentList.get(2), "SLAVE"); idealState.setRebalanceMode(IdealState.RebalanceMode.CUSTOMIZED); _gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, DATABASE, idealState); } private void verifyMastership(List<String> _assignmentList) throws Exception { String instance = _assignmentList.get(0); boolean isMasterSwitchedToCorrectInstance = TestHelper.verify(() -> { ExternalView externalView = _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, DATABASE); if (externalView == null) { return false; } Map<String, String> stateMap = externalView.getStateMap(DATABASE + "_0"); if (stateMap == null) { return false; } return "MASTER".equals(stateMap.get(instance)); }, TestHelper.WAIT_DURATION); Assert.assertTrue(isMasterSwitchedToCorrectInstance); } }
9,660
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestTaskThreadLeak.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Set; import org.apache.helix.TestHelper; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.model.IdealState; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConstants; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.WorkflowConfig; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestTaskThreadLeak extends TaskTestBase { private int _threadCountBefore = 0; @BeforeClass public void beforeClass() throws Exception { _threadCountBefore = getThreadCount("TaskStateModelFactory"); setSingleTestEnvironment(); _numNodes = 1; super.beforeClass(); } @Test public void testTaskThreadCount() throws InterruptedException { String queueName = "myTestJobQueue"; JobQueue.Builder queueBuilder = new JobQueue.Builder(queueName); String lastJob = null; for (int i = 0; i < 5; i++) { String db = TestHelper.getTestMethodName() + "_" + i; _gSetupTool.addResourceToCluster(CLUSTER_NAME, db, 20, MASTER_SLAVE_STATE_MODEL, IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, 1); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND).setTargetResource(db) .setNumConcurrentTasksPerInstance(100); queueBuilder.addJob(db + "_job", jobBuilder); lastJob = db + "_job"; } queueBuilder .setWorkflowConfig(new WorkflowConfig.Builder(queueName).setParallelJobs(10).build()); _driver.start(queueBuilder.build()); String nameSpacedJob = TaskUtil.getNamespacedJobName(queueName, lastJob); _driver.pollForJobState(queueName, nameSpacedJob, TaskState.COMPLETED); int threadCountAfter = getThreadCount("TaskStateModelFactory"); Assert.assertTrue( (threadCountAfter - _threadCountBefore) <= TaskConstants.DEFAULT_TASK_THREAD_POOL_SIZE + 1); } private int getThreadCount(String threadPrefix) { int count = 0; Set<Thread> allThreads = Thread.getAllStackTraces().keySet(); for (Thread t : allThreads) { if (t.getName().contains(threadPrefix)) { count ++; } } return count; } }
9,661
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestUserContentStore.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.Task; import org.apache.helix.task.TaskCallbackContext; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.UserContentStore; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestUserContentStore extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; // Setup cluster and instances _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < _numNodes; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } // start dummy participants for (int i = 0; i < _numNodes; i++) { final String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); // Set task callbacks Map<String, TaskFactory> taskFactoryReg = new HashMap<String, TaskFactory>(); taskFactoryReg.put("ContentStoreTask", new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new ContentStoreTask(); } }); taskFactoryReg.put("TaskOne", new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new TaskOne(); } }); taskFactoryReg.put("TaskTwo", new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new TaskTwo(); } }); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // Register a Task state model factory. StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } // Start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // Start an admin connection _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _driver = new TaskDriver(_manager); } @Test public void testWorkflowAndJobTaskUserContentStore() throws InterruptedException { String jobName = TestHelper.getTestMethodName(); Workflow.Builder workflowBuilder = new Workflow.Builder(jobName); List<TaskConfig> taskConfigs = Lists.newArrayListWithCapacity(1); Map<String, String> taskConfigMap = Maps.newHashMap(); TaskConfig taskConfig1 = new TaskConfig("ContentStoreTask", taskConfigMap); taskConfigs.add(taskConfig1); Map<String, String> jobCommandMap = Maps.newHashMap(); jobCommandMap.put("Timeout", "1000"); JobConfig.Builder jobBuilder = new JobConfig.Builder().setCommand("DummyCommand") .addTaskConfigs(taskConfigs).setWorkflow(jobName) .setJobCommandConfigMap(jobCommandMap); workflowBuilder.addJob(jobName, jobBuilder); _driver.start(workflowBuilder.build()); _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); Assert .assertEquals(_driver.getWorkflowContext(jobName).getWorkflowState(), TaskState.COMPLETED); } @Test public void testJobContentPutAndGetWithDependency() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder queueBuilder = TaskTestUtil.buildJobQueue(queueName, 0, 100); List<TaskConfig> taskConfigs1 = Lists.newArrayListWithCapacity(1); List<TaskConfig> taskConfigs2 = Lists.newArrayListWithCapacity(1); Map<String, String> taskConfigMap1 = Maps.newHashMap(); Map<String, String> taskConfigMap2 = Maps.newHashMap(); TaskConfig taskConfig1 = new TaskConfig("TaskOne", taskConfigMap1); TaskConfig taskConfig2 = new TaskConfig("TaskTwo", taskConfigMap2); taskConfigs1.add(taskConfig1); taskConfigs2.add(taskConfig2); Map<String, String> jobCommandMap = Maps.newHashMap(); jobCommandMap.put("Timeout", "1000"); JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setCommand("DummyCommand").addTaskConfigs(taskConfigs1) .setJobCommandConfigMap(jobCommandMap).setWorkflow(queueName); JobConfig.Builder jobBuilder2 = new JobConfig.Builder().setCommand("DummyCommand").addTaskConfigs(taskConfigs2) .setJobCommandConfigMap(jobCommandMap).setWorkflow(queueName); queueBuilder.enqueueJob(queueName + 0, jobBuilder1); queueBuilder.enqueueJob(queueName + 1, jobBuilder2); _driver.start(queueBuilder.build()); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, queueName + 1), TaskState.COMPLETED); Assert.assertEquals(_driver.getWorkflowContext(queueName) .getJobState(TaskUtil.getNamespacedJobName(queueName, queueName + 1)), TaskState.COMPLETED); } private static class ContentStoreTask extends UserContentStore implements Task { @Override public TaskResult run() { putUserContent("ContentTest", "Value1", Scope.JOB); putUserContent("ContentTest", "Value2", Scope.WORKFLOW); putUserContent("ContentTest", "Value3", Scope.TASK); if (!getUserContent("ContentTest", Scope.JOB).equals("Value1") || !getUserContent( "ContentTest", Scope.WORKFLOW).equals("Value2") || !getUserContent("ContentTest", Scope.TASK).equals("Value3")) { return new TaskResult(TaskResult.Status.FAILED, null); } return new TaskResult(TaskResult.Status.COMPLETED, null); } @Override public void cancel() { } } private static class TaskOne extends UserContentStore implements Task { @Override public TaskResult run() { putUserContent("RaceTest", "RaceValue", Scope.WORKFLOW); return new TaskResult(TaskResult.Status.COMPLETED, null); } @Override public void cancel() { } } private static class TaskTwo extends UserContentStore implements Task { @Override public TaskResult run() { if (!getUserContent("RaceTest", Scope.WORKFLOW).equals("RaceValue")) { return new TaskResult(TaskResult.Status.FAILED, null); } return new TaskResult(TaskResult.Status.COMPLETED, null); } @Override public void cancel() { } } }
9,662
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestWorkflowJobDependency.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowConfig; import org.apache.helix.task.WorkflowContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestWorkflowJobDependency extends TaskTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestWorkflowJobDependency.class); @BeforeClass public void beforeClass() throws Exception { _numDbs = 5; _numPartitions = 1; _partitionVary = false; super.beforeClass(); } @Test public void testWorkflowWithOutDependencies() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); // Workflow setup LOG.info("Start setup for workflow: " + workflowName); Workflow.Builder builder = new Workflow.Builder(workflowName); for (int i = 0; i < _numDbs; i++) { // Let each job delay for 2 secs. JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE", "MASTER")) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); String jobName = "job" + _testDbs.get(i); builder.addJob(jobName, jobConfig); } // Start workflow Workflow workflow = builder.build(); _driver.start(workflow); // Wait until the workflow completes _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName); long startTime = workflowContext.getStartTime(); long finishTime = workflowContext.getFinishTime(); // Update the start time range. for (String jobName : workflow.getJobConfigs().keySet()) { JobContext context = _driver.getJobContext(jobName); LOG.info(String.format("JOB: %s starts from %s finishes at %s.", jobName, context.getStartTime(), context.getFinishTime())); // Find job start time range. startTime = Math.max(context.getStartTime(), startTime); finishTime = Math.min(context.getFinishTime(), finishTime); } // All jobs have a valid overlap time range. Assert.assertTrue(startTime <= finishTime); } @Test public void testWorkflowWithDependencies() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); final int PARALLEL_NUM = 2; // Workflow setup WorkflowConfig.Builder workflowcfgBuilder = new WorkflowConfig.Builder().setWorkflowId(workflowName).setParallelJobs(PARALLEL_NUM); Workflow.Builder builder = new Workflow.Builder(workflowName); builder.setWorkflowConfig(workflowcfgBuilder.build()); builder.addParentChildDependency("job" + _testDbs.get(0), "job" + _testDbs.get(1)); for (int i = 0; i < 2; i++) { JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) .setTargetResource(_testDbs.get(i)) .setTargetPartitionStates(Sets.newHashSet("SLAVE", "MASTER")) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); String jobName = "job" + _testDbs.get(i); builder.addJob(jobName, jobConfig); } // Start workflow Workflow workflow = builder.build(); _driver.start(workflow); // Wait until the workflow completes _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED); JobContext context1 = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "job" + _testDbs.get(0))); JobContext context2 = _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "job" + _testDbs.get(1))); Assert.assertTrue(context2.getStartTime() - context1.getFinishTime() >= 0L); } }
9,663
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestWorkflowAndJobPoll.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.TestHelper; import org.apache.helix.task.TaskState; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestWorkflowAndJobPoll extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); } @Test public void testWorkflowPoll() throws InterruptedException { String jobResource = TestHelper.getTestMethodName(); Workflow.Builder builder = WorkflowGenerator.generateDefaultSingleJobWorkflowBuilder(jobResource); _driver.start(builder.build()); TaskState polledState = _driver.pollForWorkflowState(jobResource, 4000L, TaskState.COMPLETED, TaskState.FAILED); Assert.assertEquals(TaskState.COMPLETED, polledState); } @Test public void testJobPoll() throws InterruptedException { String jobResource = TestHelper.getTestMethodName(); Workflow.Builder builder = WorkflowGenerator.generateDefaultSingleJobWorkflowBuilder(jobResource); _driver.start(builder.build()); TaskState polledState = _driver .pollForJobState(jobResource, String.format("%s_%s", jobResource, jobResource), 4000L, TaskState.COMPLETED, TaskState.FAILED); Assert.assertEquals(TaskState.COMPLETED, polledState); } }
9,664
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestStopWorkflowWithExecutionDelay.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableMap; import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This test checks whether workflow stop works properly with execution delay set. */ public class TestStopWorkflowWithExecutionDelay extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); } @Test public void testStopWorkflowWithExecutionDelay() throws Exception { // Execution Delay is set to be 20 milliseconds. Any delay that causes the job to go to the // inflightjob queue is sufficient for this test. final long executionDelay = 20L; // Timeout per task has been set to be a large number. final long timeout = 60000L; String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); // Workflow DAG Schematic: // JOB0 // /\ // / \ // / \ // JOB1 JOB2 JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setTimeoutPerTask(timeout).setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")); JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setTimeoutPerTask(timeout).setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")); JobConfig.Builder jobBuilder3 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setTimeoutPerTask(timeout).setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000")); builder.addParentChildDependency("JOB0", "JOB1"); builder.addParentChildDependency("JOB0", "JOB2"); builder.addJob("JOB0", jobBuilder.setExecutionDelay(executionDelay)); builder.addJob("JOB1", jobBuilder2); builder.addJob("JOB2", jobBuilder3); _driver.start(builder.build()); // Wait until Workflow Context is created. and running. _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); // Check the Job0 is running. _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "JOB0"), TaskState.IN_PROGRESS); // Stop the workflow _driver.stop(workflowName); _driver.pollForWorkflowState(workflowName, TaskState.STOPPED); } }
9,665
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/WorkflowGenerator.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.Workflow; /** * Convenience class for generating various test workflows */ public class WorkflowGenerator { public static final String DEFAULT_TGT_DB = "TestDB"; public static final String JOB_NAME_1 = "SomeJob1"; public static final String JOB_NAME_2 = "SomeJob2"; public static final Map<String, String> DEFAULT_JOB_CONFIG; public static final Map<String, String> DEFAULT_JOB_CONFIG_NOT_TARGETED; static { Map<String, String> tmpMap = new TreeMap<String, String>(); tmpMap.put("Command", MockTask.TASK_COMMAND); tmpMap.put("TimeoutPerPartition", String.valueOf(10 * 1000)); DEFAULT_JOB_CONFIG_NOT_TARGETED = Collections.unmodifiableMap(new TreeMap<>(tmpMap)); tmpMap.put("TargetResource", DEFAULT_TGT_DB); tmpMap.put("TargetPartitionStates", "MASTER"); DEFAULT_JOB_CONFIG = Collections.unmodifiableMap(tmpMap); } public static final Map<String, String> DEFAULT_COMMAND_CONFIG; static { Map<String, String> tmpMap = new TreeMap<String, String>(); tmpMap.put("Timeout", String.valueOf(2000)); DEFAULT_COMMAND_CONFIG = Collections.unmodifiableMap(tmpMap); } public static Workflow.Builder generateDefaultSingleJobWorkflowBuilder(String jobName) { JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(DEFAULT_COMMAND_CONFIG); return generateSingleJobWorkflowBuilder(jobName, jobBuilder); } public static Workflow.Builder generateNonTargetedSingleWorkflowBuilder(String jobName) { JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(DEFAULT_JOB_CONFIG_NOT_TARGETED); jobBuilder.setJobCommandConfigMap(DEFAULT_COMMAND_CONFIG); // Create 5 TaskConfigs List<TaskConfig> taskConfigs = new ArrayList<>(); for (int i = 0; i < 5; i++) { TaskConfig.Builder taskConfigBuilder = new TaskConfig.Builder(); taskConfigBuilder.setTaskId("task_" + i); taskConfigBuilder.addConfig("Timeout", String.valueOf(2000)); taskConfigBuilder.setCommand(MockTask.TASK_COMMAND); taskConfigs.add(taskConfigBuilder.build()); } jobBuilder.addTaskConfigs(taskConfigs); return generateSingleJobWorkflowBuilder(jobName, jobBuilder); } public static Workflow.Builder generateSingleJobWorkflowBuilder(String jobName, JobConfig.Builder jobBuilder) { return new Workflow.Builder(jobName).addJobConfig(jobName, jobBuilder); } public static Workflow.Builder generateDefaultRepeatedJobWorkflowBuilder(String workflowName) { Workflow.Builder builder = new Workflow.Builder(workflowName); builder.addParentChildDependency(JOB_NAME_1, JOB_NAME_2); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(DEFAULT_COMMAND_CONFIG); builder.addJob(JOB_NAME_1, jobBuilder); builder.addJob(JOB_NAME_2, jobBuilder); return builder; } public static Workflow.Builder generateDefaultRepeatedJobWorkflowBuilder(String workflowName, int jobCount) { Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(DEFAULT_COMMAND_CONFIG); builder.addJob(JOB_NAME_1, jobBuilder); for (int i = 0; i < jobCount - 1; i++) { String jobName = JOB_NAME_2 + "-" + i; builder.addParentChildDependency(JOB_NAME_1, jobName); builder.addJob(jobName, jobBuilder); } return builder; } }
9,666
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailure.java
package org.apache.helix.integration.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.ExternalView; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobContext; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskResult; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskSynchronizedTestBase; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.util.TestInputLoader; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public final class TestJobFailure extends TaskSynchronizedTestBase { private final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[_numNodes]; _numNodes = 2; _numPartitions = 2; _numReplicas = 1; // only Master, no Slave _numDbs = 1; _gSetupTool.addCluster(CLUSTER_NAME, true); setupParticipants(); setupDBs(); startParticipants(); createManagers(); _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX); _controller.syncStart(); Thread.sleep(1000L); // Wait for cluster to setup. } private static final String EXPECTED_ENDING_STATE = "ExpectedEndingState"; private static int testNum = 0; @Test(dataProvider = "testJobFailureInput") public void testNormalJobFailure(String comment, List<String> taskStates, List<String> expectedTaskEndingStates, String expectedJobEndingStates, String expectedWorkflowEndingStates) throws Exception { final String JOB_NAME = "test_job"; final String WORKFLOW_NAME = TestHelper.getTestMethodName() + testNum++; System.out.println("Test case comment: " + comment); Map<String, Map<String, String>> targetPartitionConfigs = createPartitionConfig(taskStates, expectedTaskEndingStates); JobConfig.Builder firstJobBuilder = new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME) .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name())) .setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.TARGET_PARTITION_CONFIG, MockTask.serializeTargetPartitionConfig(targetPartitionConfigs))); Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW_NAME).addJob(JOB_NAME, firstJobBuilder); _driver.start(workflowBuilder.build()); _driver.pollForJobState(WORKFLOW_NAME, TaskUtil.getNamespacedJobName(WORKFLOW_NAME, JOB_NAME), TaskState.valueOf(expectedJobEndingStates)); _driver.pollForWorkflowState(WORKFLOW_NAME, TaskState.valueOf(expectedWorkflowEndingStates)); JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, JOB_NAME)); for (int pId : jobContext.getPartitionSet()) { Map<String, String> targetPartitionConfig = targetPartitionConfigs.get(jobContext.getTargetForPartition(pId)); Assert .assertTrue(Arrays.asList(targetPartitionConfig.get(EXPECTED_ENDING_STATE).split("\\s+")) .contains(jobContext.getPartitionState(pId).name())); } } @DataProvider(name = "testJobFailureInput") public Object[][] loadtestJobFailureInput() { String[] params = { "comment", "taskStates", "expectedTaskEndingStates", "expectedJobEndingStates", "expectedWorkflowEndingStates" }; return TestInputLoader.loadTestInputs("TestJobFailure.json", params); } private Map<String, Map<String, String>> createPartitionConfig(List<String> taskStates, List<String> expectedTaskEndingStates) throws Exception { Map<String, Map<String, String>> targetPartitionConfigs = new HashMap<>(); // Make sure external view has been created for the resource Assert.assertTrue(TestHelper.verify(() -> { ExternalView externalView = _manager.getClusterManagmentTool().getResourceExternalView(CLUSTER_NAME, DB_NAME); return externalView != null; }, TestHelper.WAIT_DURATION)); ExternalView externalView = _manager.getClusterManagmentTool().getResourceExternalView(CLUSTER_NAME, DB_NAME); Set<String> partitionSet = externalView.getPartitionSet(); if (taskStates.size() != partitionSet.size()) { throw new IllegalArgumentException( "Input size does not match number of partitions for target resource: " + DB_NAME); } int i = 0; // Set job command configs for target partitions(order doesn't matter) according to specified // task states. for (String partition : partitionSet) { Map<String, String> config = new HashMap<>(); if (taskStates.get(i).equals(TaskPartitionState.COMPLETED.name())) { config.put(MockTask.TASK_RESULT_STATUS, TaskResult.Status.COMPLETED.name()); } else if (taskStates.get(i).equals(TaskPartitionState.TASK_ERROR.name())) { config.put(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FAILED.name()); } else if (taskStates.get(i).equals(TaskPartitionState.TASK_ABORTED.name())) { config.put(MockTask.TASK_RESULT_STATUS, TaskResult.Status.FATAL_FAILED.name()); } else if (taskStates.get(i).equals(TaskPartitionState.RUNNING.name())) { config.put(MockTask.JOB_DELAY, "99999999"); } else { throw new IllegalArgumentException("Invalid taskStates input: " + taskStates.get(i)); } config.put(EXPECTED_ENDING_STATE, expectedTaskEndingStates.get(i)); targetPartitionConfigs.put(partition, config); i++; } return targetPartitionConfigs; } }
9,667
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/multizk/TestMultiInMultiZk.java
package org.apache.helix.integration.multizk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.TestHelper; import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; import org.apache.helix.zookeeper.constant.RoutingDataReaderType; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.apache.helix.zookeeper.impl.client.FederatedZkClient; import org.apache.helix.zookeeper.routing.RoutingDataManager; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Op; import org.apache.zookeeper.ZooDefs; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Date; import java.util.List; import java.util.Arrays; /** * This class test multi implementation in FederatedZkClient. Extends MultiZkTestBase as the test require a multi zk * server setup. */ public class TestMultiInMultiZk extends MultiZkTestBase { private static final String _className = TestHelper.getTestClassName(); @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); // Routing data may be set by other tests using the same endpoint; reset() for good measure RoutingDataManager.getInstance().reset(true); // Create a FederatedZkClient for admin work try { _zkClient = new FederatedZkClient(new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() .setRoutingDataSourceEndpoint(_msdsEndpoint + "," + ZK_PREFIX + ZK_START_PORT) .setRoutingDataSourceType(RoutingDataReaderType.HTTP_ZK_FALLBACK.name()).build(), new RealmAwareZkClient.RealmAwareZkClientConfig()); _zkClient.setZkSerializer(new ZNRecordSerializer()); } catch (Exception ex) { for (StackTraceElement elm : ex.getStackTrace()) { System.out.println(elm); } } } /** * Calling multi on op of different realms/servers. * Should fail. */ @Test public void testMultiDiffRealm() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); List<Op> ops = Arrays.asList( Op.create(CLUSTER_LIST.get(0), new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create(CLUSTER_LIST.get(1), new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create(CLUSTER_LIST.get(2), new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create(CLUSTER_LIST.get(0) + "/test", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); try { //Execute transactional support on operations and verify they were run _zkClient.multi(ops); Assert.fail("Should have thrown an exception. Cannot run multi on ops of different servers."); } catch (IllegalArgumentException e) { boolean pathExists = _zkClient.exists("/" + CLUSTER_LIST.get(0) + "/test"); Assert.assertFalse(pathExists, "Path should not have been created."); } System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } }
9,668
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/multizk/MultiZkTestBase.java
package org.apache.helix.integration.multizk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.google.common.collect.ImmutableList; import org.apache.helix.HelixAdmin; import org.apache.helix.SystemPropertyKeys; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.msdcommon.mock.MockMetadataStoreDirectoryServer; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.participant.statemachine.StateModelFactory; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.zookeeper.api.client.HelixZkClient; import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory; import org.apache.helix.zookeeper.zkclient.ZkServer; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.HashSet; import java.util.Collections; /** * This class sets up the clusters and zk servers for multiple zk server testing. */ public class MultiZkTestBase { protected static final int NUM_ZK = 3; protected static final Map<String, ZkServer> ZK_SERVER_MAP = new HashMap<>(); protected static final Map<String, HelixZkClient> ZK_CLIENT_MAP = new HashMap<>(); protected static final Map<String, ClusterControllerManager> MOCK_CONTROLLERS = new HashMap<>(); protected final Set<MockParticipantManager> MOCK_PARTICIPANTS = new HashSet<>(); protected static final List<String> CLUSTER_LIST = ImmutableList.of("CLUSTER_1", "CLUSTER_2", "CLUSTER_3"); protected MockMetadataStoreDirectoryServer _msds; protected static final Map<String, Collection<String>> _rawRoutingData = new HashMap<>(); protected RealmAwareZkClient _zkClient; protected HelixAdmin _zkHelixAdmin; // Save System property configs from before this test and pass onto after the test protected final Map<String, String> _configStore = new HashMap<>(); protected static final String ZK_PREFIX = "localhost:"; protected static final int ZK_START_PORT = 8977; protected String _msdsEndpoint; @BeforeClass public void beforeClass() throws Exception { // Create 3 in-memory zookeepers and routing mapping for (int i = 0; i < NUM_ZK; i++) { String zkAddress = ZK_PREFIX + (ZK_START_PORT + i); ZK_SERVER_MAP.put(zkAddress, TestHelper.startZkServer(zkAddress)); ZK_CLIENT_MAP.put(zkAddress, DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer()))); // One cluster per ZkServer created _rawRoutingData.put(zkAddress, Collections.singletonList("/" + CLUSTER_LIST.get(i))); } // Create a Mock MSDS final String msdsHostName = "localhost"; final int msdsPort = 11117; final String msdsNamespace = "multiZkTest"; _msdsEndpoint = "http://" + msdsHostName + ":" + msdsPort + "/admin/v2/namespaces/" + msdsNamespace; _msds = new MockMetadataStoreDirectoryServer(msdsHostName, msdsPort, msdsNamespace, _rawRoutingData); _msds.startServer(); // Save previously-set system configs String prevMultiZkEnabled = System.getProperty(SystemPropertyKeys.MULTI_ZK_ENABLED); String prevMsdsServerEndpoint = System.getProperty(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY); if (prevMultiZkEnabled != null) { _configStore.put(SystemPropertyKeys.MULTI_ZK_ENABLED, prevMultiZkEnabled); } if (prevMsdsServerEndpoint != null) { _configStore .put(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY, prevMsdsServerEndpoint); } // Turn on multiZk mode in System config System.setProperty(SystemPropertyKeys.MULTI_ZK_ENABLED, "true"); } @AfterClass public void afterClass() throws Exception { try { // Kill all mock controllers and participants MOCK_CONTROLLERS.values().forEach(ClusterControllerManager::syncStop); if (!MOCK_PARTICIPANTS.isEmpty()){ MOCK_PARTICIPANTS.forEach(mockParticipantManager -> { mockParticipantManager.syncStop(); StateMachineEngine stateMachine = mockParticipantManager.getStateMachineEngine(); if (stateMachine != null) { StateModelFactory stateModelFactory = stateMachine.getStateModelFactory("Task"); if (stateModelFactory instanceof TaskStateModelFactory) { ((TaskStateModelFactory) stateModelFactory).shutdown(); } } }); } // Tear down all clusters CLUSTER_LIST.forEach(cluster -> TestHelper.dropCluster(cluster, _zkClient)); // Verify that all clusters are gone in each zookeeper Assert.assertTrue(TestHelper.verify(() -> { for (Map.Entry<String, HelixZkClient> zkClientEntry : ZK_CLIENT_MAP.entrySet()) { List<String> children = zkClientEntry.getValue().getChildren("/"); if (children.stream().anyMatch(CLUSTER_LIST::contains)) { return false; } } return true; }, TestHelper.WAIT_DURATION)); } finally { // Tear down zookeepers ZK_CLIENT_MAP.forEach((zkAddress, zkClient) -> zkClient.close()); ZK_SERVER_MAP.forEach((zkAddress, zkServer) -> zkServer.shutdown()); // Stop MockMSDS _msds.stopServer(); // Close ZK client connections if (_zkHelixAdmin != null) { _zkHelixAdmin.close(); } if (_zkClient != null && !_zkClient.isClosed()) { _zkClient.close(); } // Restore System property configs if (_configStore.containsKey(SystemPropertyKeys.MULTI_ZK_ENABLED)) { System.setProperty(SystemPropertyKeys.MULTI_ZK_ENABLED, _configStore.get(SystemPropertyKeys.MULTI_ZK_ENABLED)); } else { System.clearProperty(SystemPropertyKeys.MULTI_ZK_ENABLED); } if (_configStore.containsKey(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY)) { System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY, _configStore.get(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY)); } else { System.clearProperty(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY); } } } }
9,669
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/multizk/TestMultiZkConnectionConfig.java
package org.apache.helix.integration.multizk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.lang.IllegalStateException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import com.google.common.collect.ImmutableMap; import org.apache.helix.AccessOption; import org.apache.helix.BaseDataAccessor; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixAdmin; import org.apache.helix.HelixException; import org.apache.helix.HelixCloudProperty; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.HelixManagerProperty; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.api.config.RebalanceConfig; import org.apache.helix.cloud.constants.CloudProvider; import org.apache.helix.controller.rebalancer.DelayedAutoRebalancer; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.integration.task.MockTask; import org.apache.helix.integration.task.WorkflowGenerator; import org.apache.helix.manager.zk.HelixManagerStateListener; import org.apache.helix.manager.zk.ZKHelixAdmin; import org.apache.helix.manager.zk.ZKUtil; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.manager.zk.ZKHelixManager; import org.apache.helix.model.CloudConfig; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.msdcommon.constant.MetadataStoreRoutingConstants; import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; import org.apache.helix.msdcommon.mock.MockMetadataStoreDirectoryServer; import org.apache.helix.store.HelixPropertyStore; import org.apache.helix.store.zk.ZkHelixPropertyStore; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.Workflow; import org.apache.helix.task.WorkflowContext; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; import org.apache.helix.zookeeper.api.client.ZkClientType; import org.apache.helix.zookeeper.constant.RoutingDataReaderType; import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.exception.MultiZkException; import org.apache.helix.zookeeper.impl.client.FederatedZkClient; import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory; import org.apache.helix.zookeeper.routing.RoutingDataManager; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Some Helix user do not have multizk routing configs in jvm system config but pass * in through RealAwareZkConnectionConfig. * This test class will not set jvm routing zk config and test Helix functionality. * Tests were similar to TestMultiZkHelixJavaApis but without "MSDS_SERVER_ENDPOINT_KEY" * in system property */ public class TestMultiZkConnectionConfig extends MultiZkTestBase { protected ClusterSetup _clusterSetupZkAddr; protected ClusterSetup _clusterSetupBuilder; protected RealmAwareZkClient.RealmAwareZkConnectionConfig _invalidZkConnectionConfig; protected RealmAwareZkClient.RealmAwareZkConnectionConfig _validZkConnectionConfig; // For testing different MSDS endpoint configs. private static final String CLUSTER_ONE = CLUSTER_LIST.get(0); private static final String CLUSTER_FOUR = "CLUSTER_4"; private static String _className = TestHelper.getTestClassName(); @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); // Routing data may be set by other tests using the same endpoint; reset() for good measure RoutingDataManager.getInstance().reset(true); // Create a FederatedZkClient for admin work _zkClient = new FederatedZkClient(new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() .setRoutingDataSourceEndpoint(_msdsEndpoint + "," + ZK_PREFIX + ZK_START_PORT) .setRoutingDataSourceType(RoutingDataReaderType.HTTP_ZK_FALLBACK.name()).build(), new RealmAwareZkClient.RealmAwareZkClientConfig()); _zkClient.setZkSerializer(new ZNRecordSerializer()); System.out.println("end start"); } public void beforeApiClass() throws Exception { beforeClass(); // MSDS endpoint: http://localhost:11117/admin/v2/namespaces/multiZkTest System.setProperty(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY, _msdsEndpoint); // Routing data may be set by other tests using the same endpoint; reset() for good measure RoutingDataManager.getInstance().reset(true); // Create a FederatedZkClient for admin work _zkClient = new FederatedZkClient(new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder().build(), new RealmAwareZkClient.RealmAwareZkClientConfig()); System.out.println("end start"); } /** * Test cluster creation according to the pre-set routing mapping. * Helix Java API tested is ClusterSetup in this method. */ @Test public void testCreateClusters() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); setupCluster(); createClusters(_clusterSetupZkAddr); verifyClusterCreation(_clusterSetupZkAddr); createClusters(_clusterSetupBuilder); verifyClusterCreation(_clusterSetupBuilder); // Create clusters again to continue with testing createClusters(_clusterSetupBuilder); _clusterSetupZkAddr.close(); _clusterSetupBuilder.close(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } public void setupCluster() { // Create two ClusterSetups using two different constructors // Note: ZK Address here could be anything because multiZk mode is on (it will be ignored) _clusterSetupZkAddr = new ClusterSetup(_zkClient); _clusterSetupBuilder = new ClusterSetup.Builder().setRealmAwareZkConnectionConfig( new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() .setRoutingDataSourceEndpoint(_msdsEndpoint + "," + ZK_PREFIX + ZK_START_PORT) .setRoutingDataSourceType(RoutingDataReaderType.HTTP_ZK_FALLBACK.name()).build()) .build(); } public void createClusters(ClusterSetup clusterSetup) { // Create clusters for (String clusterName : CLUSTER_LIST) { clusterSetup.addCluster(clusterName, false); } } public void verifyClusterCreation(ClusterSetup clusterSetup) { // Verify that clusters have been created correctly according to routing mapping _rawRoutingData.forEach((zkAddress, cluster) -> { // Note: clusterNamePath already contains "/" String clusterNamePath = cluster.iterator().next(); // Check with single-realm ZkClients Assert.assertTrue(ZK_CLIENT_MAP.get(zkAddress).exists(clusterNamePath)); // Check with realm-aware ZkClient (federated) Assert.assertTrue(_zkClient.exists(clusterNamePath)); // Remove clusters clusterSetup .deleteCluster(clusterNamePath.substring(1)); // Need to remove "/" at the beginning }); } /** * Test Helix Participant creation and addition. * Helix Java APIs tested in this method are: * ZkHelixAdmin and ZKHelixManager (mock participant/controller) */ @Test(dependsOnMethods = "testCreateClusters") public void testCreateParticipants() throws Exception { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); // Create two ClusterSetups using two different constructors // Note: ZK Address here could be anything because multiZk mode is on (it will be ignored) RealmAwareZkClient.RealmAwareZkConnectionConfig zkConnectionConfig = new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() .setRoutingDataSourceEndpoint(_msdsEndpoint + "," + ZK_PREFIX + ZK_START_PORT) .setRoutingDataSourceType(RoutingDataReaderType.HTTP_ZK_FALLBACK.name()).build(); HelixAdmin helixAdminBuilder = new ZKHelixAdmin.Builder().setRealmAwareZkConnectionConfig(zkConnectionConfig).build(); _zkHelixAdmin = new ZKHelixAdmin.Builder().setRealmAwareZkConnectionConfig(zkConnectionConfig).build(); String participantNamePrefix = "Node_"; int numParticipants = 5; createParticipantsAndVerify(helixAdminBuilder, numParticipants, participantNamePrefix); // Create mock controller and participants for next tests for (String cluster : CLUSTER_LIST) { // Start a controller // Note: in multiZK mode, ZK Addr is ignored RealmAwareZkClient.RealmAwareZkConnectionConfig zkConnectionConfigCls = new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() .setRoutingDataSourceEndpoint(_msdsEndpoint + "," + ZK_PREFIX + ZK_START_PORT) .setRoutingDataSourceType(RoutingDataReaderType.HTTP_ZK_FALLBACK.name()) .setZkRealmShardingKey("/" + cluster).build(); HelixManagerProperty.Builder propertyBuilder = new HelixManagerProperty.Builder(); HelixManagerProperty helixManagerProperty = propertyBuilder.setRealmAWareZkConnectionConfig(zkConnectionConfigCls).build(); ClusterControllerManager mockController = new ClusterControllerManager(cluster, helixManagerProperty); mockController.syncStart(); MOCK_CONTROLLERS.put(cluster, mockController); for (int i = 0; i < numParticipants; i++) { // Note: in multiZK mode, ZK Addr is ignored InstanceConfig instanceConfig = new InstanceConfig(participantNamePrefix + i); helixAdminBuilder.addInstance(cluster, instanceConfig); MockParticipantManager mockNode = new MockParticipantManager(cluster, participantNamePrefix + i, helixManagerProperty, 10, null); // Register task state model for task framework testing in later methods Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(MockTask.TASK_COMMAND, MockTask::new); // Register a Task state model factory. StateMachineEngine stateMachine = mockNode.getStateMachineEngine(); stateMachine .registerStateModelFactory("Task", new TaskStateModelFactory(mockNode, taskFactoryReg)); mockNode.syncStart(); MOCK_PARTICIPANTS.add(mockNode); } // Check that mockNodes are up Assert.assertTrue(TestHelper .verify(() -> helixAdminBuilder.getInstancesInCluster(cluster).size() == numParticipants, TestHelper.WAIT_DURATION)); } helixAdminBuilder.close(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } protected void createParticipantsAndVerify(HelixAdmin admin, int numParticipants, String participantNamePrefix) { // Create participants in clusters Set<String> participantNames = new HashSet<>(); CLUSTER_LIST.forEach(cluster -> { for (int i = 0; i < numParticipants; i++) { String participantName = participantNamePrefix + i; participantNames.add(participantName); InstanceConfig instanceConfig = new InstanceConfig(participantNamePrefix + i); admin.addInstance(cluster, instanceConfig); } }); // Verify participants have been created properly _rawRoutingData.forEach((zkAddress, cluster) -> { // Note: clusterNamePath already contains "/" String clusterNamePath = cluster.iterator().next(); // Check with single-realm ZkClients List<String> instances = ZK_CLIENT_MAP.get(zkAddress).getChildren(clusterNamePath + "/INSTANCES"); Assert.assertEquals(new HashSet<>(instances), participantNames); // Check with realm-aware ZkClient (federated) instances = _zkClient.getChildren(clusterNamePath + "/INSTANCES"); Assert.assertEquals(new HashSet<>(instances), participantNames); // Remove Participants participantNames.forEach(participant -> { InstanceConfig instanceConfig = new InstanceConfig(participant); admin.dropInstance(clusterNamePath.substring(1), instanceConfig); }); }); } /** * Test creation of HelixManager and makes sure it connects correctly. */ @Test(dependsOnMethods = "testCreateParticipants") public void testZKHelixManager() throws Exception { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); String clusterName = "CLUSTER_1"; String participantName = "HelixManager"; InstanceConfig instanceConfig = new InstanceConfig(participantName); _zkHelixAdmin.addInstance(clusterName, instanceConfig); createZkConnectionConfigs(clusterName); HelixManagerProperty.Builder propertyBuilder = new HelixManagerProperty.Builder(); try { HelixManager invalidManager = HelixManagerFactory .getZKHelixManager(clusterName, participantName, InstanceType.PARTICIPANT, null, propertyBuilder.setRealmAWareZkConnectionConfig(_invalidZkConnectionConfig).build()); Assert.fail("Should see a HelixException here because the connection config doesn't have the " + "sharding key set!"); } catch (HelixException e) { // Expected } // Connect as a participant HelixManager managerParticipant = HelixManagerFactory .getZKHelixManager(clusterName, participantName, InstanceType.PARTICIPANT, null, propertyBuilder.setRealmAWareZkConnectionConfig(_validZkConnectionConfig).build()); managerParticipant.connect(); // Connect as an administrator HelixManager managerAdministrator = HelixManagerFactory .getZKHelixManager(clusterName, participantName, InstanceType.ADMINISTRATOR, null, propertyBuilder.setRealmAWareZkConnectionConfig(_validZkConnectionConfig).build()); managerAdministrator.connect(); // Perform assert checks to make sure the manager can read and register itself as a participant InstanceConfig instanceConfigRead = managerAdministrator.getClusterManagmentTool() .getInstanceConfig(clusterName, participantName); Assert.assertNotNull(instanceConfigRead); Assert.assertEquals(instanceConfig.getInstanceName(), participantName); Assert.assertNotNull(managerAdministrator.getHelixDataAccessor().getProperty( managerAdministrator.getHelixDataAccessor().keyBuilder().liveInstance(participantName))); // Clean up managerParticipant.disconnect(); managerAdministrator.disconnect(); _zkHelixAdmin.dropInstance(clusterName, instanceConfig); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } protected void createZkConnectionConfigs(String clusterName) { RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder connectionConfigBuilder = new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder(); // Try with a connection config without ZK realm sharding key set (should fail) _invalidZkConnectionConfig = connectionConfigBuilder.build(); _validZkConnectionConfig = connectionConfigBuilder .setRoutingDataSourceEndpoint(_msdsEndpoint + "," + ZK_PREFIX + ZK_START_PORT) .setRoutingDataSourceType(RoutingDataReaderType.HTTP_ZK_FALLBACK.name()) .setZkRealmShardingKey("/" + clusterName).build(); } /** * Test creation of HelixManager and makes sure it connects correctly. */ @Test(dependsOnMethods = "testZKHelixManager") public void testZKHelixManagerCloudConfig() throws Exception { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); String clusterName = "CLUSTER_1"; String participantName = "HelixManager"; InstanceConfig instanceConfig = new InstanceConfig(participantName); _zkHelixAdmin.addInstance(clusterName, instanceConfig); HelixManagerProperty.Builder propertyBuilder = new HelixManagerProperty.Builder(); // create a dummy cloud config and pass to ManagerFactory. It should be overwritten by // a default config because there is no CloudConfig ZNode in ZK. CloudConfig.Builder cloudConfigBuilder = new CloudConfig.Builder(); cloudConfigBuilder.setCloudEnabled(true); // Set to Customized so CloudInfoSources and CloudInfoProcessorName will be read from cloud config // instead of properties cloudConfigBuilder.setCloudProvider(CloudProvider.CUSTOMIZED); cloudConfigBuilder.setCloudID("TestID"); List<String> infoURL = new ArrayList<String>(); infoURL.add("TestURL"); cloudConfigBuilder.setCloudInfoSources(infoURL); cloudConfigBuilder.setCloudInfoProcessorName("TestProcessor"); CloudConfig cloudConfig = cloudConfigBuilder.build(); HelixCloudProperty oldCloudProperty = new HelixCloudProperty(cloudConfig); HelixManagerProperty helixManagerProperty = propertyBuilder.setRealmAWareZkConnectionConfig(_validZkConnectionConfig) .setHelixCloudProperty(oldCloudProperty).build(); // Cloud property populated with fields defined in cloud config oldCloudProperty.populateFieldsWithCloudConfig(cloudConfig); // Add some property fields to cloud property that are not in cloud config Properties properties = new Properties(); oldCloudProperty.setCustomizedCloudProperties(properties); class TestZKHelixManager extends ZKHelixManager { public TestZKHelixManager(String clusterName, String participantName, InstanceType instanceType, String zkAddress, HelixManagerStateListener stateListener, HelixManagerProperty helixManagerProperty) { super(clusterName, participantName, instanceType, zkAddress, stateListener, helixManagerProperty); } public HelixManagerProperty getHelixManagerProperty() { return _helixManagerProperty; } } // Connect as a participant TestZKHelixManager managerParticipant = new TestZKHelixManager(clusterName, participantName, InstanceType.PARTICIPANT, null, null, helixManagerProperty); managerParticipant.connect(); HelixCloudProperty newCloudProperty = managerParticipant.getHelixManagerProperty().getHelixCloudProperty(); // Test reading from zk cloud config overwrite property fields included in cloud config Assert.assertFalse(newCloudProperty.getCloudEnabled()); Assert.assertNull(newCloudProperty.getCloudId()); Assert.assertNull(newCloudProperty.getCloudProvider()); // Test non-cloud config fields are not overwritten after reading cloud config from zk Assert.assertEquals(newCloudProperty.getCustomizedCloudProperties(), properties); Assert.assertEquals(newCloudProperty.getCloudInfoSources(), infoURL); Assert.assertEquals(newCloudProperty.getCloudInfoProcessorName(), "TestProcessor"); // Clean up managerParticipant.disconnect(); _zkHelixAdmin.dropInstance(clusterName, instanceConfig); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } private void setupApiCluster() { // Create two ClusterSetups using two different constructors // Note: ZK Address here could be anything because multiZk mode is on (it will be ignored) _clusterSetupZkAddr = new ClusterSetup(ZK_SERVER_MAP.keySet().iterator().next()); _clusterSetupBuilder = new ClusterSetup.Builder().build(); } private void createApiZkConnectionConfigs(String clusterName) { RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder connectionConfigBuilder = new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder(); // Try with a connection config without ZK realm sharding key set (should fail) _invalidZkConnectionConfig = connectionConfigBuilder.build(); _validZkConnectionConfig = connectionConfigBuilder.setZkRealmShardingKey("/" + clusterName).build(); } @Test (dependsOnMethods = "testZKHelixManagerCloudConfig") public void testApiCreateClusters() throws Exception { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); super.afterClass(); beforeApiClass(); setupApiCluster(); createClusters(_clusterSetupZkAddr); verifyClusterCreation(_clusterSetupZkAddr); createClusters(_clusterSetupBuilder); verifyClusterCreation(_clusterSetupBuilder); // Create clusters again to continue with testing createClusters(_clusterSetupBuilder); _clusterSetupZkAddr.close(); _clusterSetupBuilder.close(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } @Test(dependsOnMethods = "testApiCreateClusters") public void testApiCreateParticipants() throws Exception { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); testCreateParticipants(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } @Test(dependsOnMethods = "testApiCreateParticipants") public void testApiZKHelixManager() throws Exception { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); testZKHelixManager(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } @Test(dependsOnMethods = "testApiZKHelixManager") public void testApiZKHelixManagerCloudConfig() throws Exception { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); //todo testZKHelixManagerCloudConfig(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } @Test(dependsOnMethods = "testApiZKHelixManager") public void testZkUtil() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); CLUSTER_LIST.forEach(cluster -> { _zkHelixAdmin.getInstancesInCluster(cluster).forEach(instance -> ZKUtil .isInstanceSetup("DummyZk", cluster, instance, InstanceType.PARTICIPANT)); }); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } /** * Create resources and see if things get rebalanced correctly. * Helix Java API tested in this methods are: * ZkBaseDataAccessor * ZkHelixClusterVerifier (BestPossible) */ @Test(dependsOnMethods = "testZkUtil") public void testCreateAndRebalanceResources() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); BaseDataAccessor<ZNRecord> dataAccessorZkAddr = new ZkBaseDataAccessor<>("DummyZk"); BaseDataAccessor<ZNRecord> dataAccessorBuilder = new ZkBaseDataAccessor.Builder<ZNRecord>().build(); String resourceNamePrefix = "DB_"; int numResources = 5; int numPartitions = 3; Map<String, Map<String, ZNRecord>> idealStateMap = new HashMap<>(); for (String cluster : CLUSTER_LIST) { Set<String> resourceNames = new HashSet<>(); Set<String> liveInstancesNames = new HashSet<>(dataAccessorZkAddr .getChildNames("/" + cluster + "/LIVEINSTANCES", AccessOption.PERSISTENT)); for (int i = 0; i < numResources; i++) { String resource = cluster + "_" + resourceNamePrefix + i; _zkHelixAdmin.addResource(cluster, resource, numPartitions, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _zkHelixAdmin.rebalance(cluster, resource, 3); resourceNames.add(resource); // Update IdealState fields with ZkBaseDataAccessor String resourcePath = "/" + cluster + "/IDEALSTATES/" + resource; ZNRecord is = dataAccessorZkAddr.get(resourcePath, null, AccessOption.PERSISTENT); is.setSimpleField(RebalanceConfig.RebalanceConfigProperty.REBALANCER_CLASS_NAME.name(), DelayedAutoRebalancer.class.getName()); is.setSimpleField(RebalanceConfig.RebalanceConfigProperty.REBALANCE_STRATEGY.name(), CrushEdRebalanceStrategy.class.getName()); dataAccessorZkAddr.set(resourcePath, is, AccessOption.PERSISTENT); idealStateMap.computeIfAbsent(cluster, recordList -> new HashMap<>()) .putIfAbsent(is.getId(), is); // Save ZNRecord for comparison later } // Create a verifier to make sure all resources have been rebalanced ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(cluster).setResources(resourceNames) .setExpectLiveInstances(liveInstancesNames) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME).build(); try { Assert.assertTrue(verifier.verifyByPolling()); } finally { verifier.close(); } } // Using the ZkBaseDataAccessor created using the Builder, check that the correct IS is read for (String cluster : CLUSTER_LIST) { Map<String, ZNRecord> savedIdealStates = idealStateMap.get(cluster); List<String> resources = dataAccessorBuilder .getChildNames("/" + cluster + "/IDEALSTATES", AccessOption.PERSISTENT); resources.forEach(resource -> { ZNRecord is = dataAccessorBuilder .get("/" + cluster + "/IDEALSTATES/" + resource, null, AccessOption.PERSISTENT); Assert .assertEquals(is.getSimpleFields(), savedIdealStates.get(is.getId()).getSimpleFields()); }); } dataAccessorZkAddr.close(); dataAccessorBuilder.close(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } /** * This method tests ConfigAccessor. */ @Test(dependsOnMethods = "testCreateAndRebalanceResources") public void testConfigAccessor() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); // Build two ConfigAccessors to read and write: // 1. ConfigAccessor using a deprecated constructor // 2. ConfigAccessor using the Builder ConfigAccessor configAccessorZkAddr = new ConfigAccessor("DummyZk"); ConfigAccessor configAccessorBuilder = new ConfigAccessor.Builder().build(); setClusterConfigAndVerify(configAccessorZkAddr); setClusterConfigAndVerify(configAccessorBuilder); configAccessorZkAddr.close(); configAccessorBuilder.close(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } private void setClusterConfigAndVerify(ConfigAccessor configAccessorMultiZk) { _rawRoutingData.forEach((zkAddr, clusterNamePathList) -> { // Need to rid of "/" because this is a sharding key String cluster = clusterNamePathList.iterator().next().substring(1); ClusterConfig clusterConfig = new ClusterConfig(cluster); clusterConfig.getRecord().setSimpleField("configAccessor", cluster); configAccessorMultiZk.setClusterConfig(cluster, clusterConfig); // Now check with a single-realm ConfigAccessor ConfigAccessor configAccessorSingleZk = new ConfigAccessor.Builder().setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkAddress(zkAddr).build(); Assert.assertEquals(configAccessorSingleZk.getClusterConfig(cluster), clusterConfig); // Also check with a single-realm dedicated ZkClient ZNRecord clusterConfigRecord = ZK_CLIENT_MAP.get(zkAddr).readData("/" + cluster + "/CONFIGS/CLUSTER/" + cluster); Assert.assertEquals(clusterConfigRecord, clusterConfig.getRecord()); // Clean up clusterConfig = new ClusterConfig(cluster); configAccessorMultiZk.setClusterConfig(cluster, clusterConfig); }); } /** * This test submits multiple tasks to be run. * The Helix Java APIs tested in this method are TaskDriver (HelixManager) and * ZkHelixPropertyStore/ZkCacheBaseDataAccessor. */ @Test(dependsOnMethods = "testConfigAccessor") public void testTaskFramework() throws InterruptedException { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); // Note: TaskDriver is like HelixManager - it only operates on one designated // Create TaskDrivers for all clusters Map<String, TaskDriver> taskDriverMap = new HashMap<>(); MOCK_CONTROLLERS .forEach((cluster, controller) -> taskDriverMap.put(cluster, new TaskDriver(controller))); // Create a Task Framework workload and start Workflow workflow = WorkflowGenerator.generateNonTargetedSingleWorkflowBuilder("job").build(); for (TaskDriver taskDriver : taskDriverMap.values()) { taskDriver.start(workflow); } // Use multi-ZK ZkHelixPropertyStore/ZkCacheBaseDataAccessor to query for workflow/job states HelixPropertyStore<ZNRecord> propertyStore = new ZkHelixPropertyStore.Builder<ZNRecord>().build(); for (Map.Entry<String, TaskDriver> entry : taskDriverMap.entrySet()) { String cluster = entry.getKey(); TaskDriver driver = entry.getValue(); // Wait until workflow has completed TaskState wfStateFromTaskDriver = driver.pollForWorkflowState(workflow.getName(), TaskState.COMPLETED); String workflowContextPath = "/" + cluster + "/PROPERTYSTORE/TaskRebalancer/" + workflow.getName() + "/Context"; ZNRecord workflowContextRecord = propertyStore.get(workflowContextPath, null, AccessOption.PERSISTENT); WorkflowContext context = new WorkflowContext(workflowContextRecord); // Compare the workflow state read from PropertyStore and TaskDriver Assert.assertEquals(context.getWorkflowState(), wfStateFromTaskDriver); } System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } /** * This method tests that ZKHelixAdmin::getClusters() works in multi-zk environment. */ @Test(dependsOnMethods = "testTaskFramework") public void testGetAllClusters() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); Assert.assertEquals(new HashSet<>(_zkHelixAdmin.getClusters()), new HashSet<>(CLUSTER_LIST)); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } /** * This method tests that GenericBaseDataAccessorBuilder and GenericZkHelixApiBuilder work as * expected. This test focuses on various usage scenarios for ZkBaseDataAccessor. * * Use cases tested: * - Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, ZK address set * - Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, ZK address not set, ZK sharding key set * - Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, ZK address set, ZK sharding key set (ZK addr should override) * - Create ZkBaseDataAccessor, single-realm, sharedZkClient, ZK address set * - Create ZkBaseDataAccessor, single-realm, sharedZkClient, ZK address not set, ZK sharding key set * - Create ZkBaseDataAccessor, single-realm, sharedZkClient, ZK address set, ZK sharding key set (ZK addr should override) * - Create ZkBaseDataAccessor, single-realm, federated ZkClient (should fail) * - Create ZkBaseDataAccessor, multi-realm, dedicated ZkClient (should fail) * - Create ZkBaseDataAccessor, multi-realm, shared ZkClient (should fail) * - Create ZkBaseDataAccessor, multi-realm, federated ZkClient, ZkAddress set (should fail) * - Create ZkBaseDataAccessor, multi-realm, federated ZkClient, Zk sharding key set (should fail because by definition, multi-realm can access multiple sharding keys) * - Create ZkBaseDataAccessor, multi-realm, federated ZkClient * - Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, No ZkAddress set, ConnectionConfig has an invalid ZK sharding key (should fail because it cannot find a valid ZK to connect to) */ @Test(dependsOnMethods = "testGetAllClusters") public void testGenericBaseDataAccessorBuilder() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); // Custom session timeout value is used to count active connections in SharedZkClientFactory int customSessionTimeout = 10000; String firstZkAddress = ZK_PREFIX + ZK_START_PORT; // has "CLUSTER_1" String firstClusterPath = "/CLUSTER_1"; String secondClusterPath = "/CLUSTER_2"; ZkBaseDataAccessor.Builder<ZNRecord> zkBaseDataAccessorBuilder = new ZkBaseDataAccessor.Builder<>(); RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder connectionConfigBuilder = new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder(); connectionConfigBuilder.setSessionTimeout(customSessionTimeout); BaseDataAccessor<ZNRecord> accessor; // Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, ZK address set int currentSharedZkClientActiveConnectionCount = SharedZkClientFactory.getInstance().getActiveConnectionCount(); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.DEDICATED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.assertTrue(accessor.exists(firstClusterPath, AccessOption.PERSISTENT)); Assert.assertFalse(accessor.exists(secondClusterPath, AccessOption.PERSISTENT)); // Check that no extra connection has been created //Assert.assertEquals(SharedZkClientFactory.getInstance().getActiveConnectionCount(), // currentSharedZkClientActiveConnectionCount); accessor.close(); // Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, ZK address not set, ZK sharding key set connectionConfigBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkRealmShardingKey(firstClusterPath); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.DEDICATED).setZkAddress(null) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.assertTrue(accessor.exists(firstClusterPath, AccessOption.PERSISTENT)); Assert.assertFalse(accessor.exists(secondClusterPath, AccessOption.PERSISTENT)); Assert.assertEquals(SharedZkClientFactory.getInstance().getActiveConnectionCount(), currentSharedZkClientActiveConnectionCount); accessor.close(); // Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, ZK address set, ZK sharding key set (ZK addr should override) connectionConfigBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkRealmShardingKey(secondClusterPath); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.DEDICATED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.assertTrue(accessor.exists(firstClusterPath, AccessOption.PERSISTENT)); Assert.assertFalse(accessor.exists(secondClusterPath, AccessOption.PERSISTENT)); Assert.assertEquals(SharedZkClientFactory.getInstance().getActiveConnectionCount(), currentSharedZkClientActiveConnectionCount); accessor.close(); // Create ZkBaseDataAccessor, single-realm, sharedZkClient, ZK address set currentSharedZkClientActiveConnectionCount = SharedZkClientFactory.getInstance().getActiveConnectionCount(); connectionConfigBuilder.setZkRealmShardingKey(null).setRealmMode(null); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.SHARED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.assertTrue(accessor.exists(firstClusterPath, AccessOption.PERSISTENT)); Assert.assertFalse(accessor.exists(secondClusterPath, AccessOption.PERSISTENT)); // Add one to active connection count since this is a shared ZkClientType Assert.assertEquals(SharedZkClientFactory.getInstance().getActiveConnectionCount(), currentSharedZkClientActiveConnectionCount + 1); accessor.close(); // Create ZkBaseDataAccessor, single-realm, sharedZkClient, ZK address not set, ZK sharding key set connectionConfigBuilder.setZkRealmShardingKey(firstClusterPath) .setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.SHARED).setZkAddress(null) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.assertTrue(accessor.exists(firstClusterPath, AccessOption.PERSISTENT)); Assert.assertFalse(accessor.exists(secondClusterPath, AccessOption.PERSISTENT)); // Add one to active connection count since this is a shared ZkClientType Assert.assertEquals(SharedZkClientFactory.getInstance().getActiveConnectionCount(), currentSharedZkClientActiveConnectionCount + 1); accessor.close(); // Create ZkBaseDataAccessor, single-realm, sharedZkClient, ZK address set, ZK sharding key set // (ZK address should override the sharding key setting) connectionConfigBuilder.setZkRealmShardingKey(secondClusterPath) .setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.SHARED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.assertTrue(accessor.exists(firstClusterPath, AccessOption.PERSISTENT)); Assert.assertFalse(accessor.exists(secondClusterPath, AccessOption.PERSISTENT)); // Add one to active connection count since this is a shared ZkClientType Assert.assertEquals(SharedZkClientFactory.getInstance().getActiveConnectionCount(), currentSharedZkClientActiveConnectionCount + 1); accessor.close(); // Create ZkBaseDataAccessor, single-realm, federated ZkClient (should fail) connectionConfigBuilder.setZkRealmShardingKey(null).setRealmMode(null); try { accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.FEDERATED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.fail("SINGLE_REALM and FEDERATED ZkClientType are an invalid combination!"); } catch (HelixException e) { // Expected } // Create ZkBaseDataAccessor, multi-realm, dedicated ZkClient (should fail) try { accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.MULTI_REALM) .setZkClientType(ZkClientType.DEDICATED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.fail("MULTI_REALM and DEDICATED ZkClientType are an invalid combination!"); } catch (HelixException e) { // Expected } // Create ZkBaseDataAccessor, multi-realm, shared ZkClient (should fail) try { accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.MULTI_REALM) .setZkClientType(ZkClientType.SHARED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.fail("MULTI_REALM and SHARED ZkClientType are an invalid combination!"); } catch (HelixException e) { // Expected } // Create ZkBaseDataAccessor, multi-realm, federated ZkClient, ZkAddress set (should fail) try { accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.MULTI_REALM) .setZkClientType(ZkClientType.FEDERATED).setZkAddress(firstZkAddress) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.fail("MULTI_REALM and FEDERATED ZkClientType do not connect to one ZK!"); } catch (HelixException e) { // Expected } // Create ZkBaseDataAccessor, multi-realm, federated ZkClient, Zk sharding key set (should fail // because by definition, multi-realm can access multiple sharding keys) try { connectionConfigBuilder.setZkRealmShardingKey(firstClusterPath) .setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.MULTI_REALM) .setZkClientType(ZkClientType.FEDERATED).setZkAddress(null) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.fail("MULTI_REALM and FEDERATED ZkClientType do not connect to one ZK!"); } catch (HelixException e) { // Expected } // Create ZkBaseDataAccessor, multi-realm, federated ZkClient connectionConfigBuilder.setZkRealmShardingKey(null).setRealmMode(null); accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.MULTI_REALM) .setZkClientType(ZkClientType.FEDERATED).setZkAddress(null) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.assertTrue(accessor.exists(firstClusterPath, AccessOption.PERSISTENT)); Assert.assertTrue(accessor.exists(secondClusterPath, AccessOption.PERSISTENT)); accessor.close(); // Create ZkBaseDataAccessor, single-realm, dedicated ZkClient, No ZkAddress set, // ConnectionConfig has an invalid ZK sharding key (should fail because it cannot find a valid // ZK to connect to) connectionConfigBuilder.setZkRealmShardingKey("/NonexistentShardingKey"); try { accessor = zkBaseDataAccessorBuilder.setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) .setZkClientType(ZkClientType.DEDICATED).setZkAddress(null) .setRealmAwareZkConnectionConfig(connectionConfigBuilder.build()).build(); Assert.fail("Should fail because it cannot find a valid ZK to connect to!"); } catch (NoSuchElementException e) { // Expected because the sharding key wouldn't be found } System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } /** * Tests Helix Java APIs which use different MSDS endpoint configs. Java API should * only connect to the configured MSDS but not the others. The APIs are explicitly tested are: * - ClusterSetup * - HelixAdmin * - ZkUtil * - HelixManager * - BaseDataAccessor * - ConfigAccessor */ @Test(dependsOnMethods = "testGenericBaseDataAccessorBuilder") public void testDifferentMsdsEndpointConfigs() throws IOException, InvalidRoutingDataException { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); final String zkAddress = ZK_SERVER_MAP.keySet().iterator().next(); final Map<String, Collection<String>> secondRoutingData = ImmutableMap.of(zkAddress, Collections.singletonList(formPath(CLUSTER_FOUR))); MockMetadataStoreDirectoryServer secondMsds = new MockMetadataStoreDirectoryServer("localhost", 11118, "multiZkTest", secondRoutingData); final RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig = new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() .setRoutingDataSourceType(RoutingDataReaderType.HTTP.name()) .setRoutingDataSourceEndpoint(secondMsds.getEndpoint()).build(); secondMsds.startServer(); try { // Verify ClusterSetup verifyClusterSetupMsdsEndpoint(connectionConfig); // Verify HelixAdmin verifyHelixAdminMsdsEndpoint(connectionConfig); // Verify ZKUtil verifyZkUtilMsdsEndpoint(); // Verify HelixManager verifyHelixManagerMsdsEndpoint(); // Verify BaseDataAccessor verifyBaseDataAccessorMsdsEndpoint(connectionConfig); // Verify ConfigAccessor verifyConfigAccessorMsdsEndpoint(connectionConfig); } finally { RealmAwareZkClient zkClient = new FederatedZkClient(connectionConfig, new RealmAwareZkClient.RealmAwareZkClientConfig()); TestHelper.dropCluster(CLUSTER_FOUR, zkClient); zkClient.close(); secondMsds.stopServer(); } System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } private void verifyHelixManagerMsdsEndpoint() { System.out.println("Start " + TestHelper.getTestMethodName()); // Mock participants are already created and started in the previous test. // The mock participant only connects to MSDS configured in system property, // but not the other. final MockParticipantManager manager = MOCK_PARTICIPANTS.iterator().next(); verifyMsdsZkRealm(CLUSTER_FOUR, false, () -> manager.getZkClient().exists(formPath(CLUSTER_FOUR))); verifyMsdsZkRealm(CLUSTER_ONE, true, () -> manager.getZkClient().exists(formPath(manager.getClusterName()))); if (manager.getZkClient() != null) { System.out.println("zk client is not yet null2"); } } private void verifyBaseDataAccessorMsdsEndpoint( RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig) { System.out.println("Start " + TestHelper.getTestMethodName()); // MSDS endpoint is not configured in builder, so config in system property is used. BaseDataAccessor<ZNRecord> firstDataAccessor = new ZkBaseDataAccessor.Builder<ZNRecord>().build(); // Create base data accessor with MSDS endpoint configured in builder. BaseDataAccessor<ZNRecord> secondDataAccessor = new ZkBaseDataAccessor.Builder<ZNRecord>().setRealmAwareZkConnectionConfig(connectionConfig) .build(); String methodName = TestHelper.getTestMethodName(); String clusterOnePath = formPath(CLUSTER_ONE, methodName); String clusterFourPath = formPath(CLUSTER_FOUR, methodName); ZNRecord record = new ZNRecord(methodName); try { firstDataAccessor.create(clusterOnePath, record, AccessOption.PERSISTENT); secondDataAccessor.create(clusterFourPath, record, AccessOption.PERSISTENT); // Verify data accessors that they could only talk to their own configured MSDS endpoint: // either being set in builder or system property. Assert.assertTrue(firstDataAccessor.exists(clusterOnePath, AccessOption.PERSISTENT)); verifyMsdsZkRealm(CLUSTER_FOUR, false, () -> firstDataAccessor.exists(clusterFourPath, AccessOption.PERSISTENT)); Assert.assertTrue(secondDataAccessor.exists(clusterFourPath, AccessOption.PERSISTENT)); verifyMsdsZkRealm(CLUSTER_ONE, false, () -> secondDataAccessor.exists(clusterOnePath, AccessOption.PERSISTENT)); firstDataAccessor.remove(clusterOnePath, AccessOption.PERSISTENT); secondDataAccessor.remove(clusterFourPath, AccessOption.PERSISTENT); Assert.assertFalse(firstDataAccessor.exists(clusterOnePath, AccessOption.PERSISTENT)); Assert.assertFalse(secondDataAccessor.exists(clusterFourPath, AccessOption.PERSISTENT)); } finally { firstDataAccessor.close(); secondDataAccessor.close(); } } private void verifyClusterSetupMsdsEndpoint( RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig) { System.out.println("Start " + TestHelper.getTestMethodName()); ClusterSetup firstClusterSetup = new ClusterSetup.Builder().build(); ClusterSetup secondClusterSetup = new ClusterSetup.Builder().setRealmAwareZkConnectionConfig(connectionConfig).build(); try { verifyMsdsZkRealm(CLUSTER_ONE, true, () -> firstClusterSetup.addCluster(CLUSTER_ONE, false)); verifyMsdsZkRealm(CLUSTER_FOUR, false, () -> firstClusterSetup.addCluster(CLUSTER_FOUR, false)); verifyMsdsZkRealm(CLUSTER_FOUR, true, () -> secondClusterSetup.addCluster(CLUSTER_FOUR, false)); verifyMsdsZkRealm(CLUSTER_ONE, false, () -> secondClusterSetup.addCluster(CLUSTER_ONE, false)); } finally { firstClusterSetup.close(); secondClusterSetup.close(); } } private void verifyZkUtilMsdsEndpoint() { System.out.println("Start " + TestHelper.getTestMethodName()); String dummyZkAddress = "dummyZkAddress"; // MSDS endpoint 1 verifyMsdsZkRealm(CLUSTER_ONE, true, () -> ZKUtil.getChildren(dummyZkAddress, formPath(CLUSTER_ONE))); // Verify MSDS endpoint 2 is not used by this ZKUtil. verifyMsdsZkRealm(CLUSTER_FOUR, false, () -> ZKUtil.getChildren(dummyZkAddress, formPath(CLUSTER_FOUR))); } private void verifyHelixAdminMsdsEndpoint( RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig) { System.out.println("Start " + TestHelper.getTestMethodName()); HelixAdmin firstHelixAdmin = new ZKHelixAdmin.Builder().build(); HelixAdmin secondHelixAdmin = new ZKHelixAdmin.Builder().setRealmAwareZkConnectionConfig(connectionConfig).build(); try { verifyMsdsZkRealm(CLUSTER_ONE, true, () -> firstHelixAdmin.enableCluster(CLUSTER_ONE, true)); verifyMsdsZkRealm(CLUSTER_FOUR, false, () -> firstHelixAdmin.enableCluster(CLUSTER_FOUR, true)); verifyMsdsZkRealm(CLUSTER_FOUR, true, () -> secondHelixAdmin.enableCluster(CLUSTER_FOUR, true)); verifyMsdsZkRealm(CLUSTER_ONE, false, () -> secondHelixAdmin.enableCluster(CLUSTER_ONE, true)); } finally { firstHelixAdmin.close(); secondHelixAdmin.close(); } } private void verifyConfigAccessorMsdsEndpoint( RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig) { System.out.println("Start " + TestHelper.getTestMethodName()); ConfigAccessor firstConfigAccessor = new ConfigAccessor.Builder().build(); ConfigAccessor secondConfigAccessor = new ConfigAccessor.Builder().setRealmAwareZkConnectionConfig(connectionConfig).build(); try { verifyMsdsZkRealm(CLUSTER_ONE, true, () -> firstConfigAccessor.getClusterConfig(CLUSTER_ONE)); verifyMsdsZkRealm(CLUSTER_FOUR, false, () -> firstConfigAccessor.getClusterConfig(CLUSTER_FOUR)); verifyMsdsZkRealm(CLUSTER_FOUR, true, () -> secondConfigAccessor.getClusterConfig(CLUSTER_FOUR)); verifyMsdsZkRealm(CLUSTER_ONE, false, () -> secondConfigAccessor.getClusterConfig(CLUSTER_ONE)); } finally { firstConfigAccessor.close(); secondConfigAccessor.close(); } } private interface Operation { void run(); } private void verifyMsdsZkRealm(String cluster, boolean shouldSucceed, Operation operation) { try { operation.run(); if (!shouldSucceed) { Assert.fail("Should not connect to the MSDS that has /" + cluster); } } catch (NoSuchElementException e) { if (shouldSucceed) { Assert.fail("ZK Realm should be found for /" + cluster); } else { Assert.assertTrue(e.getMessage() .startsWith("No sharding key found within the provided path. Path: /" + cluster)); } } catch (IllegalArgumentException e) { if (shouldSucceed) { Assert.fail(formPath(cluster) + " should be a valid sharding key."); } else { String messageOne = "Given path: /" + cluster + " does not have a " + "valid sharding key or its ZK sharding key is not found in the cached routing data"; String messageTwo = "Given path: /" + cluster + "'s ZK sharding key: /" + cluster + " does not match the ZK sharding key"; Assert.assertTrue( e.getMessage().startsWith(messageOne) || e.getMessage().startsWith(messageTwo)); } } catch (HelixException e) { // NoSuchElementException: "ZK Realm not found!" is swallowed in ZKUtil.isClusterSetup() // Instead, HelixException is thrown. if (shouldSucceed) { Assert.fail("Cluster: " + cluster + " should have been setup."); } else { Assert.assertEquals("fail to get config. cluster: " + cluster + " is NOT setup.", e.getMessage()); } } catch (IllegalStateException e) { System.out.println("Exception: " + e); } } private String formPath(String... pathNames) { StringBuilder sb = new StringBuilder(); for (String name : pathNames) { sb.append('/').append(name); } return sb.toString(); } /** * Testing using ZK as the routing data source. We use BaseDataAccessor as the representative * Helix API. * Two modes are tested: ZK and HTTP-ZK fallback */ @Test(dependsOnMethods = "testDifferentMsdsEndpointConfigs") public void testZkRoutingDataSourceConfigs() { String methodName = TestHelper.getTestMethodName(); System.out.println("START " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); // Set up routing data in ZK by connecting directly to ZK BaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor.Builder<ZNRecord>().setZkAddress(ZK_PREFIX + ZK_START_PORT).build(); // Create ZK realm routing data ZNRecord _rawRoutingData.forEach((realm, keys) -> { ZNRecord znRecord = new ZNRecord(realm); znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, new ArrayList<>(keys)); accessor.set(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realm, znRecord, AccessOption.PERSISTENT); }); // Create connection configs with the source type set to each type final RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder connectionConfigBuilder = new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder(); final RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfigZk = connectionConfigBuilder.setRoutingDataSourceType(RoutingDataReaderType.ZK.name()) .setRoutingDataSourceEndpoint(ZK_PREFIX + ZK_START_PORT).build(); final RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfigHttpZkFallback = connectionConfigBuilder .setRoutingDataSourceType(RoutingDataReaderType.HTTP_ZK_FALLBACK.name()) .setRoutingDataSourceEndpoint(_msdsEndpoint + "," + ZK_PREFIX + ZK_START_PORT).build(); final RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfigHttp = connectionConfigBuilder.setRoutingDataSourceType(RoutingDataReaderType.HTTP.name()) .setRoutingDataSourceEndpoint(_msdsEndpoint).build(); // Reset cached routing data RoutingDataManager.getInstance().reset(true); // Shutdown MSDS to ensure that these accessors are able to pull routing data from ZK _msds.stopServer(); // Create a BaseDataAccessor instance with the connection config BaseDataAccessor<ZNRecord> zkBasedAccessor = new ZkBaseDataAccessor.Builder<ZNRecord>() .setRealmAwareZkConnectionConfig(connectionConfigZk).build(); BaseDataAccessor<ZNRecord> httpZkFallbackBasedAccessor = new ZkBaseDataAccessor.Builder<ZNRecord>() .setRealmAwareZkConnectionConfig(connectionConfigHttpZkFallback).build(); try { BaseDataAccessor<ZNRecord> httpBasedAccessor = new ZkBaseDataAccessor.Builder<ZNRecord>() .setRealmAwareZkConnectionConfig(connectionConfigHttp).build(); Assert.fail("Must fail with a MultiZkException because HTTP connection will be refused."); } catch (MultiZkException e) { // Okay } // Check that all clusters appear as existing to this accessor CLUSTER_LIST.forEach(cluster -> { Assert.assertTrue(zkBasedAccessor.exists("/" + cluster, AccessOption.PERSISTENT)); Assert.assertTrue(httpZkFallbackBasedAccessor.exists("/" + cluster, AccessOption.PERSISTENT)); }); // Close all connections accessor.close(); zkBasedAccessor.close(); httpZkFallbackBasedAccessor.close(); System.out.println("END " + _className + "_" + methodName + " at " + new Date(System.currentTimeMillis())); } }
9,670
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProvider.java
package org.apache.helix.integration.spectator; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.helix.AccessOption; import org.apache.helix.HelixException; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.NotificationContext; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.PropertyType; import org.apache.helix.TestHelper; import org.apache.helix.api.listeners.RoutingTableChangeListener; import org.apache.helix.common.ZkTestBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.BuiltInStateModelDefinitions; import org.apache.helix.model.CustomizedView; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.spectator.RoutingTableProvider; import org.apache.helix.spectator.RoutingTableSnapshot; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.mockito.internal.util.collections.Sets; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestRoutingTableProvider extends ZkTestBase { static final String STATE_MODEL = BuiltInStateModelDefinitions.MasterSlave.name(); static final String TEST_DB = "TestDB"; static final String CLASS_NAME = TestRoutingTableProvider.class.getSimpleName(); static final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME; static final int PARTICIPANT_NUMBER = 3; static final int PARTICIPANT_START_PORT = 12918; static final long WAIT_DURATION = 5 * 1000L; // 5 seconds static final int PARTITION_NUMBER = 20; static final int REPLICA_NUMBER = 3; private HelixManager _spectator; private List<MockParticipantManager> _participants = new ArrayList<>(); private List<String> _instances = new ArrayList<>(); private ClusterControllerManager _controller; private ZkHelixClusterVerifier _clusterVerifier; private RoutingTableProvider _routingTableProvider_default; private RoutingTableProvider _routingTableProvider_ev; private RoutingTableProvider _routingTableProvider_cs; private boolean _listenerTestResult = true; class MockRoutingTableChangeListener implements RoutingTableChangeListener { boolean routingTableChangeReceived = false; @Override public void onRoutingTableChange(RoutingTableSnapshot routingTableSnapshot, Object context) { Set<String> masterInstances = new HashSet<>(); Set<String> slaveInstances = new HashSet<>(); for (InstanceConfig config : routingTableSnapshot .getInstancesForResource(TEST_DB, "MASTER")) { masterInstances.add(config.getInstanceName()); } for (InstanceConfig config : routingTableSnapshot.getInstancesForResource(TEST_DB, "SLAVE")) { slaveInstances.add(config.getInstanceName()); } if (context != null && (!masterInstances.equals(Map.class.cast(context).get("MASTER")) || !slaveInstances.equals(Map.class.cast(context).get("SLAVE")))) { _listenerTestResult = false; } else { _listenerTestResult = true; } routingTableChangeReceived = true; } } @BeforeClass public void beforeClass() throws Exception { System.out.println( "START " + getShortClassName() + " at " + new Date(System.currentTimeMillis())); // setup storage cluster _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < PARTICIPANT_NUMBER; i++) { String instance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance); _instances.add(instance); } // start dummy participants for (int i = 0; i < PARTICIPANT_NUMBER; i++) { MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _instances.get(i)); participant.syncStart(); _participants.add(participant); } createDBInSemiAuto(_gSetupTool, CLUSTER_NAME, TEST_DB, _instances, STATE_MODEL, PARTITION_NUMBER, REPLICA_NUMBER); // start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // start speculator _spectator = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "spectator", InstanceType.SPECTATOR, ZK_ADDR); _spectator.connect(); _routingTableProvider_default = new RoutingTableProvider(_spectator); _spectator.addExternalViewChangeListener(_routingTableProvider_default); _spectator.addLiveInstanceChangeListener(_routingTableProvider_default); _spectator.addInstanceConfigChangeListener(_routingTableProvider_default); _routingTableProvider_ev = new RoutingTableProvider(_spectator); _routingTableProvider_cs = new RoutingTableProvider(_spectator, PropertyType.CURRENTSTATES); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); } @AfterClass public void afterClass() { // stop participants for (MockParticipantManager p : _participants) { p.syncStop(); } _controller.syncStop(); _routingTableProvider_default.shutdown(); _routingTableProvider_ev.shutdown(); _routingTableProvider_cs.shutdown(); _spectator.disconnect(); deleteCluster(CLUSTER_NAME); } @Test public void testInvocation() throws Exception { MockRoutingTableChangeListener routingTableChangeListener = new MockRoutingTableChangeListener(); _routingTableProvider_default .addRoutingTableChangeListener(routingTableChangeListener, null, true); // Add a routing table provider listener should trigger an execution of the // listener callbacks Assert.assertTrue(TestHelper.verify(() -> { if (!routingTableChangeListener.routingTableChangeReceived) { return false; } return true; }, TestHelper.WAIT_DURATION)); } @Test(dependsOnMethods = { "testInvocation" }) public void testRoutingTable() { Assert.assertEquals(_routingTableProvider_default.getLiveInstances().size(), _instances.size()); Assert.assertEquals(_routingTableProvider_default.getInstanceConfigs().size(), _instances.size()); Assert.assertEquals(_routingTableProvider_ev.getLiveInstances().size(), _instances.size()); Assert.assertEquals(_routingTableProvider_ev.getInstanceConfigs().size(), _instances.size()); Assert.assertEquals(_routingTableProvider_cs.getLiveInstances().size(), _instances.size()); Assert.assertEquals(_routingTableProvider_cs.getInstanceConfigs().size(), _instances.size()); validateRoutingTable(_routingTableProvider_default, Sets.newSet(_instances.get(0)), Sets.newSet(_instances.get(1), _instances.get(2))); validateRoutingTable(_routingTableProvider_ev, Sets.newSet(_instances.get(0)), Sets.newSet(_instances.get(1), _instances.get(2))); validateRoutingTable(_routingTableProvider_cs, Sets.newSet(_instances.get(0)), Sets.newSet(_instances.get(1), _instances.get(2))); Collection<String> databases = _routingTableProvider_default.getResources(); Assert.assertEquals(databases.size(), 1); } @Test(dependsOnMethods = { "testRoutingTable" }) public void testDisableInstance() throws InterruptedException { // disable the master instance String prevMasterInstance = _instances.get(0); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, false); Assert.assertTrue(_clusterVerifier.verifyByPolling()); validateRoutingTable(_routingTableProvider_default, Sets.newSet(_instances.get(1)), Sets.newSet(_instances.get(2))); validateRoutingTable(_routingTableProvider_ev, Sets.newSet(_instances.get(1)), Sets.newSet(_instances.get(2))); validateRoutingTable(_routingTableProvider_cs, Sets.newSet(_instances.get(1)), Sets.newSet(_instances.get(2))); } @Test(dependsOnMethods = { "testDisableInstance" }) public void testRoutingTableListener() throws InterruptedException { RoutingTableChangeListener routingTableChangeListener = new MockRoutingTableChangeListener(); Map<String, Set<String>> context = new HashMap<>(); context.put("MASTER", Sets.newSet(_instances.get(0))); context.put("SLAVE", Sets.newSet(_instances.get(1), _instances.get(2))); _routingTableProvider_default .addRoutingTableChangeListener(routingTableChangeListener, context, true); _routingTableProvider_default .addRoutingTableChangeListener(new MockRoutingTableChangeListener(), null, true); // reenable the master instance to cause change String prevMasterInstance = _instances.get(0); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, true); Assert.assertTrue(_clusterVerifier.verifyByPolling()); Assert.assertTrue(_listenerTestResult); } @Test(dependsOnMethods = { "testRoutingTableListener" }) public void testShutdownInstance() throws InterruptedException { // shutdown second instance. _participants.get(1).syncStop(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); Assert.assertEquals(_routingTableProvider_default.getLiveInstances().size(), _instances.size() - 1); Assert.assertEquals(_routingTableProvider_default.getInstanceConfigs().size(), _instances.size()); Assert.assertEquals(_routingTableProvider_ev.getLiveInstances().size(), _instances.size() - 1); Assert.assertEquals(_routingTableProvider_ev.getInstanceConfigs().size(), _instances.size()); Assert.assertEquals(_routingTableProvider_cs.getLiveInstances().size(), _instances.size() - 1); Assert.assertEquals(_routingTableProvider_cs.getInstanceConfigs().size(), _instances.size()); validateRoutingTable(_routingTableProvider_default, Sets.newSet(_instances.get(0)), Sets.newSet(_instances.get(2))); validateRoutingTable(_routingTableProvider_ev, Sets.newSet(_instances.get(0)), Sets.newSet(_instances.get(2))); validateRoutingTable(_routingTableProvider_cs, Sets.newSet(_instances.get(0)), Sets.newSet(_instances.get(2))); } @Test(expectedExceptions = HelixException.class, dependsOnMethods = "testShutdownInstance") public void testExternalViewWithType() { Map<PropertyType, List<String>> sourceDataTypes = new HashMap<>(); sourceDataTypes.put(PropertyType.EXTERNALVIEW, Arrays.asList("typeA")); sourceDataTypes.put(PropertyType.CUSTOMIZEDVIEW, Arrays.asList("typeA", "typeB")); RoutingTableProvider routingTableProvider; routingTableProvider = new RoutingTableProvider(_spectator, sourceDataTypes); } @Test(dependsOnMethods = "testExternalViewWithType", expectedExceptions = HelixException.class) public void testCustomizedViewWithoutType() { RoutingTableProvider routingTableProvider; routingTableProvider = new RoutingTableProvider(_spectator, PropertyType.CUSTOMIZEDVIEW); } @Test(dependsOnMethods = "testCustomizedViewWithoutType") public void testCustomizedViewCorrectConstructor() throws Exception { Map<PropertyType, List<String>> sourceDataTypes = new HashMap<>(); sourceDataTypes.put(PropertyType.CUSTOMIZEDVIEW, Arrays.asList("typeA")); CountDownLatch countDownLatch = new CountDownLatch(1); RoutingTableProvider routingTableProvider = new RoutingTableProvider(_spectator, sourceDataTypes) { @Override public void onCustomizedViewChange(List<CustomizedView> customizedViewList, NotificationContext changeContext){ countDownLatch.countDown(); super.onCustomizedViewChange(customizedViewList, changeContext); } }; CustomizedView customizedView = new CustomizedView(TEST_DB); customizedView.setState("p1", "h1", "testState"); // Clear the flag before writing to the Customized View Path String customizedViewPath = PropertyPathBuilder.customizedView(CLUSTER_NAME, "typeA", TEST_DB); _spectator.getHelixDataAccessor().getBaseDataAccessor().set(customizedViewPath, customizedView.getRecord(), AccessOption.PERSISTENT); Assert.assertTrue(countDownLatch.await(WAIT_DURATION, TimeUnit.MILLISECONDS)); _spectator.getHelixDataAccessor().getBaseDataAccessor().remove(customizedViewPath, AccessOption.PERSISTENT); routingTableProvider.shutdown(); } @Test(dependsOnMethods = "testCustomizedViewCorrectConstructor") public void testGetRoutingTableSnapshot() throws Exception { Map<PropertyType, List<String>> sourceDataTypes = new HashMap<>(); sourceDataTypes.put(PropertyType.CUSTOMIZEDVIEW, Arrays.asList("typeA", "typeB")); sourceDataTypes.put(PropertyType.EXTERNALVIEW, Collections.emptyList()); RoutingTableProvider routingTableProvider = new RoutingTableProvider(_spectator, sourceDataTypes); CustomizedView customizedView1 = new CustomizedView("Resource1"); customizedView1.setState("p1", "h1", "testState1"); customizedView1.setState("p1", "h2", "testState1"); customizedView1.setState("p2", "h1", "testState2"); customizedView1.setState("p3", "h2", "testState3"); String customizedViewPath1 = PropertyPathBuilder.customizedView(CLUSTER_NAME, "typeA", "Resource1"); CustomizedView customizedView2 = new CustomizedView("Resource2"); customizedView2.setState("p1", "h3", "testState3"); customizedView2.setState("p1", "h4", "testState2"); String customizedViewPath2 = PropertyPathBuilder.customizedView(CLUSTER_NAME, "typeB", "Resource2"); _spectator.getHelixDataAccessor().getBaseDataAccessor().set(customizedViewPath1, customizedView1.getRecord(), AccessOption.PERSISTENT); _spectator.getHelixDataAccessor().getBaseDataAccessor().set(customizedViewPath2, customizedView2.getRecord(), AccessOption.PERSISTENT); RoutingTableSnapshot routingTableSnapshot = routingTableProvider.getRoutingTableSnapshot(PropertyType.CUSTOMIZEDVIEW, "typeA"); Assert.assertEquals(routingTableSnapshot.getPropertyType(), PropertyType.CUSTOMIZEDVIEW); Assert.assertEquals(routingTableSnapshot.getCustomizedStateType(), "typeA"); routingTableSnapshot = routingTableProvider.getRoutingTableSnapshot(PropertyType.CUSTOMIZEDVIEW, "typeB"); Assert.assertEquals(routingTableSnapshot.getPropertyType(), PropertyType.CUSTOMIZEDVIEW); Assert.assertEquals(routingTableSnapshot.getCustomizedStateType(), "typeB"); // Make sure snapshot information is correct // Check resources are in a correct state boolean isRoutingTableUpdatedProperly = TestHelper.verify(() -> { Map<String, Map<String, RoutingTableSnapshot>> routingTableSnapshots = routingTableProvider.getRoutingTableSnapshots(); RoutingTableSnapshot routingTableSnapshotTypeA = routingTableSnapshots.get(PropertyType.CUSTOMIZEDVIEW.name()).get("typeA"); RoutingTableSnapshot routingTableSnapshotTypeB = routingTableSnapshots.get(PropertyType.CUSTOMIZEDVIEW.name()).get("typeB"); String typeAp1h1 = "noState"; String typeAp1h2 = "noState"; String typeAp2h1 = "noState"; String typeAp3h2 = "noState"; String typeBp1h2 = "noState"; String typeBp1h4 = "noState"; try { typeAp1h1 = routingTableSnapshotTypeA.getCustomizeViews().iterator().next() .getStateMap("p1").get("h1"); typeAp1h2 = routingTableSnapshotTypeA.getCustomizeViews().iterator().next() .getStateMap("p1").get("h2"); typeAp2h1 = routingTableSnapshotTypeA.getCustomizeViews().iterator().next() .getStateMap("p2").get("h1"); typeAp3h2 = routingTableSnapshotTypeA.getCustomizeViews().iterator().next() .getStateMap("p3").get("h2"); typeBp1h2 = routingTableSnapshotTypeB.getCustomizeViews().iterator().next() .getStateMap("p1").get("h3"); typeBp1h4 = routingTableSnapshotTypeB.getCustomizeViews().iterator().next() .getStateMap("p1").get("h4"); } catch (Exception e) { // ok because RoutingTable has not been updated yet return false; } return (routingTableSnapshots.size() == 2 && routingTableSnapshots.get(PropertyType.CUSTOMIZEDVIEW.name()).size() == 2 && typeAp1h1.equals("testState1") && typeAp1h2.equals("testState1") && typeAp2h1.equals("testState2") && typeAp3h2.equals("testState3") && typeBp1h2.equals("testState3") && typeBp1h4.equals("testState2")); }, WAIT_DURATION); Assert.assertTrue(isRoutingTableUpdatedProperly, "RoutingTable has been updated properly"); routingTableProvider.shutdown(); } private void validateRoutingTable(RoutingTableProvider routingTableProvider, Set<String> masterNodes, Set<String> slaveNodes) { IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, TEST_DB); for (String p : is.getPartitionSet()) { Set<String> masterInstances = new HashSet<>(); for (InstanceConfig config : routingTableProvider.getInstances(TEST_DB, p, "MASTER")) { masterInstances.add(config.getInstanceName()); } Set<String> slaveInstances = new HashSet<>(); for (InstanceConfig config : routingTableProvider.getInstances(TEST_DB, p, "SLAVE")) { slaveInstances.add(config.getInstanceName()); } Assert.assertEquals(masterInstances, masterNodes); Assert.assertEquals(slaveInstances, slaveNodes); } } }
9,671
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromTargetEV.java
package org.apache.helix.integration.spectator; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.PropertyType; import org.apache.helix.TestHelper; import org.apache.helix.common.ZkTestBase; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.integration.task.WorkflowGenerator; import org.apache.helix.mock.participant.MockDelayMSStateModelFactory; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.model.Message; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.spectator.RoutingTableProvider; 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 TestRoutingTableProviderFromTargetEV extends ZkTestBase { private static Logger LOG = LoggerFactory.getLogger(TestRoutingTableProviderFromTargetEV.class); private HelixManager _manager; private final String MASTER_SLAVE_STATE_MODEL = "MasterSlave"; private final int NUM_NODES = 10; protected int NUM_PARTITIONS = 20; protected int NUM_REPLICAS = 3; private final int START_PORT = 12918; private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + getShortClassName(); private MockParticipantManager[] _participants; private ClusterControllerManager _controller; private ConfigAccessor _configAccessor; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[NUM_NODES]; _gSetupTool.addCluster(CLUSTER_NAME, true); _participants = new MockParticipantManager[NUM_NODES]; for (int i = 0; i < NUM_NODES; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.addResourceToCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, NUM_PARTITIONS, MASTER_SLAVE_STATE_MODEL, IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _gSetupTool .rebalanceStorageCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, NUM_REPLICAS); for (int i = 0; i < NUM_NODES; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); // add a delayed state model StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); MockDelayMSStateModelFactory delayFactory = new MockDelayMSStateModelFactory().setDelay(-300000L); stateMachine.registerStateModelFactory(MASTER_SLAVE_STATE_MODEL, delayFactory); _participants[i].syncStart(); } _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _configAccessor = new ConfigAccessor(_gZkClient); } @AfterClass public void afterClass() throws Exception { if (_controller != null && _controller.isConnected()) { _controller.syncStop(); } for (int i = 0; i < NUM_NODES; i++) { if (_participants[i] != null && _participants[i].isConnected()) { _participants[i].syncStop(); } } if (_manager != null && _manager.isConnected()) { _manager.disconnect(); } deleteCluster(CLUSTER_NAME); } @Test(expectedExceptions = HelixException.class) public void testTargetExternalViewWithoutEnable() { new RoutingTableProvider(_manager, PropertyType.TARGETEXTERNALVIEW); } @Test (dependsOnMethods = "testTargetExternalViewWithoutEnable") public void testExternalViewDoesNotExist() { String resourceName = WorkflowGenerator.DEFAULT_TGT_DB + 1; RoutingTableProvider externalViewProvider = new RoutingTableProvider(_manager, PropertyType.EXTERNALVIEW); try { Assert.assertEquals(externalViewProvider.getInstancesForResource(resourceName, "SLAVE").size(), 0); } finally { externalViewProvider.shutdown(); } } @Test (dependsOnMethods = "testExternalViewDoesNotExist") public void testExternalViewDiffFromTargetExternalView() throws Exception { ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME); clusterConfig.enableTargetExternalView(true); clusterConfig.setPersistBestPossibleAssignment(true); _configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig); Thread.sleep(2000); RoutingTableProvider externalViewProvider = new RoutingTableProvider(_manager, PropertyType.EXTERNALVIEW); final RoutingTableProvider targetExternalViewProvider = new RoutingTableProvider(_manager, PropertyType.TARGETEXTERNALVIEW); try { // If there is a pending message. TEV reflect to its target state and EV reflect to its current state. Set<InstanceConfig> externalViewMasters = externalViewProvider.getInstancesForResource(WorkflowGenerator.DEFAULT_TGT_DB, "MASTER"); Assert.assertEquals(externalViewMasters.size(), 0); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); Assert.assertTrue(TestHelper.verify(() -> { ExternalView ev = accessor.getProperty(accessor.keyBuilder().externalView(WorkflowGenerator.DEFAULT_TGT_DB)); ExternalView tev = accessor.getProperty(accessor.keyBuilder().targetExternalView(WorkflowGenerator.DEFAULT_TGT_DB)); AtomicBoolean valid = new AtomicBoolean(true); List<String> instances = accessor.getChildNames(accessor.keyBuilder().instanceConfigs()); instances.stream().forEach(i -> { List<Message> messages = accessor.getChildValues(accessor.keyBuilder().messages(i)); messages.stream().forEach(m -> { if (!m.getFromState().equals(ev.getStateMap(m.getPartitionName()).get(i)) || !m.getToState() .equals(tev.getStateMap(m.getPartitionName()).get(i))) { valid.set(false); } }); }); return valid.get(); }, 3000)); } finally { externalViewProvider.shutdown(); targetExternalViewProvider.shutdown(); } } }
9,672
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableSnapshot.java
package org.apache.helix.integration.spectator; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.Set; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.PropertyType; import org.apache.helix.TestHelper; import org.apache.helix.common.ZkTestBase; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.spectator.RoutingTableProvider; import org.apache.helix.spectator.RoutingTableSnapshot; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestRoutingTableSnapshot extends ZkTestBase { private HelixManager _manager; private final int NUM_NODES = 10; protected int NUM_PARTITIONS = 20; protected int NUM_REPLICAS = 3; private final int START_PORT = 12918; private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + getShortClassName(); private MockParticipantManager[] _participants; private ClusterControllerManager _controller; @BeforeClass public void beforeClass() throws Exception { _participants = new MockParticipantManager[NUM_NODES]; _gSetupTool.addCluster(CLUSTER_NAME, true); _participants = new MockParticipantManager[NUM_NODES]; for (int i = 0; i < NUM_NODES; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } for (int i = 0; i < NUM_NODES; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); } @AfterClass public void afterClass() throws Exception { if (_manager != null && _manager.isConnected()) { _manager.disconnect(); } for (int i = 0; i < NUM_NODES; i++) { if (_participants[i] != null && _participants[i].isConnected()) { _participants[i].reset(); } } if (_controller != null && _controller.isConnected()) { _controller.syncStop(); } deleteCluster(CLUSTER_NAME); } @Test public void testRoutingTableSnapshot() throws InterruptedException { RoutingTableProvider routingTableProvider = new RoutingTableProvider(_manager, PropertyType.EXTERNALVIEW); try { String db1 = "TestDB-1"; _gSetupTool.addResourceToCluster(CLUSTER_NAME, db1, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db1, NUM_REPLICAS); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling()); IdealState idealState1 = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db1); RoutingTableSnapshot routingTableSnapshot = routingTableProvider.getRoutingTableSnapshot(); validateMapping(idealState1, routingTableSnapshot); Assert.assertEquals(routingTableSnapshot.getInstanceConfigs().size(), NUM_NODES); Assert.assertEquals(routingTableSnapshot.getResources().size(), 1); Assert.assertEquals(routingTableSnapshot.getLiveInstances().size(), NUM_NODES); Assert.assertEquals(routingTableSnapshot.getExternalViews().size(), 1); // 1 DB // add new DB and shutdown an instance String db2 = "TestDB-2"; _gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db2, NUM_REPLICAS); // shutdown an instance _participants[0].syncStop(); Assert.assertTrue(clusterVerifier.verifyByPolling()); // the original snapshot should not change Assert.assertEquals(routingTableSnapshot.getInstanceConfigs().size(), NUM_NODES); Assert.assertEquals(routingTableSnapshot.getResources().size(), 1); Assert.assertEquals(routingTableSnapshot.getLiveInstances().size(), NUM_NODES); RoutingTableSnapshot newRoutingTableSnapshot = routingTableProvider.getRoutingTableSnapshot(); Assert.assertEquals(newRoutingTableSnapshot.getInstanceConfigs().size(), NUM_NODES); Assert.assertEquals(newRoutingTableSnapshot.getResources().size(), 2); Assert.assertEquals(newRoutingTableSnapshot.getLiveInstances().size(), NUM_NODES - 1); Assert.assertEquals(newRoutingTableSnapshot.getExternalViews().size(), 2); // 2 DBs } finally { routingTableProvider.shutdown(); } } private void validateMapping(IdealState idealState, RoutingTableSnapshot routingTableSnapshot) { String db = idealState.getResourceName(); Set<String> partitions = idealState.getPartitionSet(); for (String partition : partitions) { List<InstanceConfig> masterInsEv = routingTableSnapshot.getInstancesForResource(db, partition, "MASTER"); Assert.assertEquals(masterInsEv.size(), 1); List<InstanceConfig> slaveInsEv = routingTableSnapshot.getInstancesForResource(db, partition, "SLAVE"); Assert.assertEquals(slaveInsEv.size(), 2); } } }
9,673
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderPeriodicRefresh.java
package org.apache.helix.integration.spectator; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.PropertyType; import org.apache.helix.TestHelper; import org.apache.helix.common.ZkTestBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.model.BuiltInStateModelDefinitions; import org.apache.helix.model.CurrentState; import org.apache.helix.model.ExternalView; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.LiveInstance; import org.apache.helix.spectator.RoutingTableProvider; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; 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 TestRoutingTableProviderPeriodicRefresh extends ZkTestBase { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TestRoutingTableProviderPeriodicRefresh.class); private static final String STATE_MODEL = BuiltInStateModelDefinitions.MasterSlave.name(); private static final String TEST_DB = "TestDB"; private static final String CLASS_NAME = TestHelper.getTestClassName(); private static final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME; private static final int PARTICIPANT_NUMBER = 3; private static final int PARTICIPANT_START_PORT = 12918; private static final int PARTITION_NUMBER = 20; private static final int REPLICA_NUMBER = 3; private static final long REFRESH_PERIOD_MS = 1000L; private HelixManager _spectator; private HelixManager _spectator_2; private HelixManager _spectator_3; private List<MockParticipantManager> _participants = new ArrayList<>(); private List<String> _instances = new ArrayList<>(); private ClusterControllerManager _controller; private ZkHelixClusterVerifier _clusterVerifier; private MockRoutingTableProvider _routingTableProvider; private MockRoutingTableProvider _routingTableProviderNoPeriodicRefresh; private MockRoutingTableProvider _routingTableProviderLongPeriodicRefresh; @BeforeClass public void beforeClass() throws Exception { System.out .println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis())); // setup storage cluster _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < PARTICIPANT_NUMBER; i++) { String instance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance); _instances.add(instance); } // start dummy participants for (int i = 0; i < PARTICIPANT_NUMBER; i++) { MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _instances.get(i)); participant.syncStart(); _participants.add(participant); } createDBInSemiAuto(_gSetupTool, CLUSTER_NAME, TEST_DB, _instances, STATE_MODEL, PARTITION_NUMBER, REPLICA_NUMBER); // start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); // start speculator - initialize it with a Mock _spectator = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "spectator", InstanceType.SPECTATOR, ZK_ADDR); _spectator.connect(); _spectator_2 = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "spectator_2", InstanceType.SPECTATOR, ZK_ADDR); _spectator_2.connect(); _spectator_3 = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "spectator_3", InstanceType.SPECTATOR, ZK_ADDR); _spectator_3.connect(); _routingTableProvider = new MockRoutingTableProvider(_spectator, PropertyType.EXTERNALVIEW, true, REFRESH_PERIOD_MS); _spectator.addExternalViewChangeListener(_routingTableProvider); _spectator.addLiveInstanceChangeListener(_routingTableProvider); _spectator.addInstanceConfigChangeListener(_routingTableProvider); _routingTableProviderNoPeriodicRefresh = new MockRoutingTableProvider(_spectator_2, PropertyType.EXTERNALVIEW, false, REFRESH_PERIOD_MS); _spectator_2.addExternalViewChangeListener(_routingTableProviderNoPeriodicRefresh); _spectator_2.addLiveInstanceChangeListener(_routingTableProviderNoPeriodicRefresh); _spectator_2.addInstanceConfigChangeListener(_routingTableProviderNoPeriodicRefresh); _routingTableProviderLongPeriodicRefresh = new MockRoutingTableProvider(_spectator_3, PropertyType.EXTERNALVIEW, true, 3000000L); _spectator_3.addExternalViewChangeListener(_routingTableProviderLongPeriodicRefresh); _spectator_3.addLiveInstanceChangeListener(_routingTableProviderLongPeriodicRefresh); _spectator_3.addInstanceConfigChangeListener(_routingTableProviderLongPeriodicRefresh); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME).build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); } @AfterClass public void afterClass() { // stop participants for (MockParticipantManager p : _participants) { p.syncStop(); } // Call shutdown to make sure they are shutting down properly _routingTableProvider.shutdown(); _routingTableProviderNoPeriodicRefresh.shutdown(); _routingTableProviderLongPeriodicRefresh.shutdown(); _controller.syncStop(); _routingTableProvider.shutdown(); _routingTableProviderNoPeriodicRefresh.shutdown(); _routingTableProviderLongPeriodicRefresh.shutdown(); _spectator.disconnect(); _spectator_2.disconnect(); _spectator_3.disconnect(); deleteCluster(CLUSTER_NAME); } public class MockRoutingTableProvider extends RoutingTableProvider { private volatile int _refreshCount = 0; private static final boolean DEBUG = false; public MockRoutingTableProvider(HelixManager helixManager, PropertyType sourceDataType, boolean isPeriodicRefreshEnabled, long periodRefreshInterval) { super(helixManager, sourceDataType, isPeriodicRefreshEnabled, periodRefreshInterval); } @Override protected synchronized void refreshExternalView(Collection<ExternalView> externalViews, Collection<InstanceConfig> instanceConfigs, Collection<LiveInstance> liveInstances, String referenceKey) { super.refreshExternalView(externalViews, instanceConfigs, liveInstances, referenceKey); _refreshCount++; if (DEBUG) { print(); } } @Override protected synchronized void refreshCurrentState( Map<String, Map<String, Map<String, CurrentState>>> currentStateMap, Collection<InstanceConfig> instanceConfigs, Collection<LiveInstance> liveInstances, String referenceKey) { super.refreshCurrentState(currentStateMap, instanceConfigs, liveInstances, "Test"); _refreshCount++; if (DEBUG) { print(); } } // Log statements for debugging purposes private void print() { logger.error("Refresh happened; count: {}", getRefreshCount()); logger.error("timestamp: {}", System.currentTimeMillis()); } synchronized int getRefreshCount() { return _refreshCount; } } @Test public void testPeriodicRefresh() throws InterruptedException { // Wait to ensure that the initial refreshes finish (not triggered by periodic refresh timer) Thread.sleep(REFRESH_PERIOD_MS * 2); // Test short refresh int prevRefreshCount = _routingTableProvider.getRefreshCount(); // Wait for more than one timer duration Thread.sleep((long) (REFRESH_PERIOD_MS * 1.5)); // The timer should have gone off, incrementing the refresh count by one or two depends on the // timing. int newRefreshCount = _routingTableProvider.getRefreshCount(); Assert.assertTrue( newRefreshCount == prevRefreshCount + 1 || newRefreshCount == prevRefreshCount + 2); // Test no periodic refresh prevRefreshCount = _routingTableProviderNoPeriodicRefresh.getRefreshCount(); // Wait Thread.sleep(REFRESH_PERIOD_MS * 2); // The timer should NOT have gone off, the refresh count must stay the same Assert.assertEquals(_routingTableProviderNoPeriodicRefresh.getRefreshCount(), prevRefreshCount); // Test long periodic refresh prevRefreshCount = _routingTableProviderLongPeriodicRefresh.getRefreshCount(); // Wait Thread.sleep(REFRESH_PERIOD_MS * 2); // The timer should NOT have gone off yet, the refresh count must stay the same Assert .assertEquals(_routingTableProviderLongPeriodicRefresh.getRefreshCount(), prevRefreshCount); } }
9,674
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromCurrentStates.java
package org.apache.helix.integration.spectator; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.lang.management.ManagementFactory; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Semaphore; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.google.common.collect.ImmutableMap; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixException; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.NotificationContext; import org.apache.helix.PropertyType; import org.apache.helix.SystemPropertyKeys; import org.apache.helix.TestHelper; import org.apache.helix.api.listeners.PreFetch; import org.apache.helix.common.ZkTestBase; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.integration.task.MockTask; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.CurrentState; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.LiveInstance; import org.apache.helix.monitoring.mbeans.MBeanRegistrar; import org.apache.helix.monitoring.mbeans.MonitorDomainNames; import org.apache.helix.monitoring.mbeans.RoutingTableProviderMonitor; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.spectator.RoutingTableProvider; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskConstants; import org.apache.helix.task.TaskDriver; import org.apache.helix.task.TaskFactory; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskStateModelFactory; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase { private HelixManager _manager; private final int NUM_NODES = 10; protected int NUM_PARTITIONS = 20; protected int NUM_REPLICAS = 3; private final int START_PORT = 12918; private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + getShortClassName(); private MockParticipantManager[] _participants; private ClusterControllerManager _controller; private MBeanServer _beanServer = ManagementFactory.getPlatformMBeanServer(); @BeforeClass public void beforeClass() throws Exception { _gSetupTool.addCluster(CLUSTER_NAME, true); _participants = new MockParticipantManager[NUM_NODES]; for (int i = 0; i < NUM_NODES; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(MockTask.TASK_COMMAND, MockTask::new); for (int i = 0; i < NUM_NODES; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory(TaskConstants.STATE_MODEL_NAME, new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); ConfigAccessor _configAccessor = _manager.getConfigAccessor(); ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME); clusterConfig.enableTargetExternalView(true); _configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig); } @AfterClass public void afterClass() throws Exception { /* * shutdown order: 1) disconnect the controller 2) disconnect participants */ if (_controller != null && _controller.isConnected()) { _controller.syncStop(); } for (int i = 0; i < NUM_NODES; i++) { if (_participants[i] != null && _participants[i].isConnected()) { _participants[i].syncStop(); } } if (_manager != null && _manager.isConnected()) { _manager.disconnect(); } deleteCluster(CLUSTER_NAME); } @Test public void testCurrentStatesRoutingTableIgnoreTaskCurrentStates() throws Exception { FlaggedCurrentStateRoutingTableProvider routingTableCurrentStates = new FlaggedCurrentStateRoutingTableProvider(_manager); Assert.assertFalse(routingTableCurrentStates.isOnStateChangeTriggered()); try { TaskDriver taskDriver = new TaskDriver(_manager); String workflowName1 = TestHelper.getTestMethodName() + "_1"; String jobName = "JOB0"; JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(workflowName1).setNumberOfTasks(NUM_NODES) .setNumConcurrentTasksPerInstance(1).setCommand(MockTask.TASK_COMMAND) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000")); Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName1).addJob(jobName, jobBuilder); taskDriver.start(workflowBuilder1.build()); taskDriver .pollForJobState(workflowName1, TaskUtil.getNamespacedJobName(workflowName1, jobName), TaskState.COMPLETED); Assert.assertFalse(routingTableCurrentStates.isOnStateChangeTriggered()); // Disable the task current path and the routing table provider should be notified System.setProperty(SystemPropertyKeys.TASK_CURRENT_STATE_PATH_DISABLED, "true"); String workflowName2 = TestHelper.getTestMethodName() + "_2"; Workflow.Builder workflowBuilder2 = new Workflow.Builder(workflowName2).addJob(jobName, jobBuilder); taskDriver.start(workflowBuilder2.build()); taskDriver .pollForJobState(workflowName2, TaskUtil.getNamespacedJobName(workflowName2, jobName), TaskState.COMPLETED); Assert.assertTrue(routingTableCurrentStates.isOnStateChangeTriggered()); System.setProperty(SystemPropertyKeys.TASK_CURRENT_STATE_PATH_DISABLED, "false"); String dbName = "testDB"; _gSetupTool.addResourceToCluster(CLUSTER_NAME, dbName, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, NUM_REPLICAS); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling()); Assert.assertTrue(routingTableCurrentStates.isOnStateChangeTriggered()); _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, dbName); } finally { routingTableCurrentStates.shutdown(); } } @Test (dependsOnMethods = "testCurrentStatesRoutingTableIgnoreTaskCurrentStates") public void testRoutingTableWithCurrentStates() throws Exception { RoutingTableProvider routingTableEV = new RoutingTableProvider(_manager, PropertyType.EXTERNALVIEW); RoutingTableProvider routingTableCurrentStates = new RoutingTableProvider(_manager, PropertyType.CURRENTSTATES); try { String db1 = "TestDB-1"; _gSetupTool.addResourceToCluster(CLUSTER_NAME, db1, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); long startTime = System.currentTimeMillis(); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db1, NUM_REPLICAS); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling()); validatePropagationLatency(PropertyType.CURRENTSTATES, System.currentTimeMillis() - startTime); IdealState idealState1 = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db1); validate(idealState1, routingTableEV, routingTableCurrentStates, 0); // add new DB String db2 = "TestDB-2"; _gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); startTime = System.currentTimeMillis(); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db2, NUM_REPLICAS); Assert.assertTrue(clusterVerifier.verifyByPolling()); validatePropagationLatency(PropertyType.CURRENTSTATES, System.currentTimeMillis() - startTime); IdealState idealState2 = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db2); validate(idealState2, routingTableEV, routingTableCurrentStates, 0); // shutdown an instance startTime = System.currentTimeMillis(); _participants[0].syncStop(); Assert.assertTrue(clusterVerifier.verifyByPolling()); validatePropagationLatency(PropertyType.CURRENTSTATES, System.currentTimeMillis() - startTime); validate(idealState1, routingTableEV, routingTableCurrentStates, 0); validate(idealState2, routingTableEV, routingTableCurrentStates, 0); } finally { routingTableEV.shutdown(); routingTableCurrentStates.shutdown(); } } private ObjectName buildObjectName(PropertyType type) throws MalformedObjectNameException { return MBeanRegistrar.buildObjectName(MonitorDomainNames.RoutingTableProvider.name(), RoutingTableProviderMonitor.CLUSTER_KEY, CLUSTER_NAME, RoutingTableProviderMonitor.DATA_TYPE_KEY, type.name()); } private void validatePropagationLatency(PropertyType type, final long upperBound) throws Exception { final ObjectName name = buildObjectName(type); Assert.assertTrue(TestHelper.verify(() -> { long stateLatency = (long) _beanServer.getAttribute(name, "StatePropagationLatencyGauge.Max"); return stateLatency > 0 && stateLatency <= upperBound; }, 1000)); } @Test(dependsOnMethods = "testRoutingTableWithCurrentStates") public void TestInconsistentStateEventProcessing() throws Exception { // This test requires an additional HelixManager since one of the provider event processing will // be blocked. HelixManager helixManager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, TestHelper.getTestMethodName(), InstanceType.SPECTATOR, ZK_ADDR); helixManager.connect(); RoutingTableProvider routingTableEV = null; BlockingCurrentStateRoutingTableProvider routingTableCS = null; int shutdownParticipantIndex = -1; try { // Prepare test environment routingTableEV = new RoutingTableProvider(helixManager, PropertyType.EXTERNALVIEW); routingTableCS = new BlockingCurrentStateRoutingTableProvider(_manager); // Ensure the current state routing table provider has been refreshed. for (String resourceName : _gSetupTool.getClusterManagementTool() .getResourcesInCluster(CLUSTER_NAME)) { IdealState idealState = _gSetupTool.getClusterManagementTool() .getResourceIdealState(CLUSTER_NAME, resourceName); validate(idealState, routingTableEV, routingTableCS, 3000); } // Blocking the current state event processing routingTableCS.setBlocking(true); // 1. Create a new resource and wait until all components process the change. // Note that since the processing of routingTableCS has been blocked, it will be stuck on the // current state change. String db = "TestDB-" + TestHelper.getTestMethodName(); _gSetupTool.addResourceToCluster(CLUSTER_NAME, db, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName()); _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, NUM_REPLICAS); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling(5000, 500)); // 2. Process one event, so the current state will be refreshed with the new DB partitions routingTableCS.proceedNewEventHandling(); IdealState idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db); String targetPartitionName = idealState.getPartitionSet().iterator().next(); // Wait until the routingtable is updated. BlockingCurrentStateRoutingTableProvider finalRoutingTableCS = routingTableCS; Assert.assertTrue(TestHelper.verify( () -> finalRoutingTableCS.getInstances(db, targetPartitionName, "MASTER").size() > 0, 2000)); String targetNodeName = routingTableCS.getInstances(db, targetPartitionName, "MASTER").get(0).getInstanceName(); // 3. Shutdown one of the instance that contains a master partition for (int i = 0; i < _participants.length; i++) { if (_participants[i].getInstanceName().equals(targetNodeName)) { shutdownParticipantIndex = i; _participants[i].syncStop(); } } Assert.assertTrue(clusterVerifier.verifyByPolling()); // 4. Process one of the stale current state event. // The expectation is that, the provider will refresh with all the latest data including the // the live instance change. Even the corresponding ZK event has not been processed yet. routingTableCS.proceedNewEventHandling(); validate(idealState, routingTableEV, routingTableCS, 3000); // 5. Unblock the event processing and let the provider to process all events. // The expectation is that, the eventual routing tables are still the same. routingTableCS.setBlocking(false); routingTableCS.proceedNewEventHandling(); // Wait for a short while so the router will process at least one event. Thread.sleep(500); // Confirm that 2 providers match eventually validate(idealState, routingTableEV, routingTableCS, 2000); } finally { if (routingTableCS != null) { routingTableCS.setBlocking(false); routingTableCS.proceedNewEventHandling(); routingTableCS.shutdown(); } if (routingTableEV != null) { routingTableEV.shutdown(); } if (shutdownParticipantIndex >= 0) { String participantName = _participants[shutdownParticipantIndex].getInstanceName(); _participants[shutdownParticipantIndex] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, participantName); _participants[shutdownParticipantIndex].syncStart(); } helixManager.disconnect(); } } @Test(dependsOnMethods = { "TestInconsistentStateEventProcessing" }) public void testWithSupportSourceDataType() { new RoutingTableProvider(_manager, PropertyType.EXTERNALVIEW).shutdown(); new RoutingTableProvider(_manager, PropertyType.TARGETEXTERNALVIEW).shutdown(); new RoutingTableProvider(_manager, PropertyType.CURRENTSTATES).shutdown(); try { new RoutingTableProvider(_manager, PropertyType.IDEALSTATES).shutdown(); Assert.fail(); } catch (HelixException ex) { Assert.assertTrue(ex.getMessage().contains("Unsupported source data type")); } } private void validate(IdealState idealState, RoutingTableProvider routingTableEV, RoutingTableProvider routingTableCurrentStates, int timeout) throws Exception { Assert.assertTrue(TestHelper .verify(() -> compare(idealState, routingTableEV, routingTableCurrentStates), timeout)); } private boolean compare(IdealState idealState, RoutingTableProvider routingTableEV, RoutingTableProvider routingTableCurrentStates) { String db = idealState.getResourceName(); Set<String> partitions = idealState.getPartitionSet(); for (String partition : partitions) { List<InstanceConfig> masterInsEv = routingTableEV.getInstancesForResource(db, partition, "MASTER"); List<InstanceConfig> masterInsCs = routingTableCurrentStates.getInstancesForResource(db, partition, "MASTER"); if (masterInsEv.size() != 1 || masterInsCs.size() != 1 || !masterInsCs.equals(masterInsEv)) { return false; } List<InstanceConfig> slaveInsEv = routingTableEV.getInstancesForResource(db, partition, "SLAVE"); List<InstanceConfig> slaveInsCs = routingTableCurrentStates.getInstancesForResource(db, partition, "SLAVE"); if (slaveInsEv.size() != 2 || slaveInsCs.size() != 2 || !new HashSet(slaveInsCs) .equals(new HashSet(slaveInsEv))) { return false; } } return true; } static class BlockingCurrentStateRoutingTableProvider extends RoutingTableProvider { private final Semaphore newEventHandlingCount = new Semaphore(0); private boolean _isBlocking = false; public BlockingCurrentStateRoutingTableProvider(HelixManager manager) { super(manager, PropertyType.CURRENTSTATES); } public void setBlocking(boolean isBlocking) { _isBlocking = isBlocking; } void proceedNewEventHandling() { newEventHandlingCount.release(); } @Override @PreFetch(enabled = false) public void onStateChange(String instanceName, List<CurrentState> statesInfo, NotificationContext changeContext) { if (_isBlocking) { try { newEventHandlingCount.acquire(); } catch (InterruptedException e) { throw new HelixException("Failed to acquire handling lock for testing."); } } super.onStateChange(instanceName, statesInfo, changeContext); } @Override @PreFetch(enabled = true) public void onLiveInstanceChange(List<LiveInstance> liveInstances, NotificationContext changeContext) { if (_isBlocking) { try { newEventHandlingCount.acquire(); } catch (InterruptedException e) { throw new HelixException("Failed to acquire handling lock for testing."); } } super.onLiveInstanceChange(liveInstances, changeContext); } } static class FlaggedCurrentStateRoutingTableProvider extends RoutingTableProvider { private boolean onStateChangeTriggered = false; public FlaggedCurrentStateRoutingTableProvider(HelixManager manager) { super(manager, PropertyType.CURRENTSTATES); } public boolean isOnStateChangeTriggered() { return onStateChangeTriggered; } @Override @PreFetch(enabled = false) public void onStateChange(String instanceName, List<CurrentState> statesInfo, NotificationContext changeContext) { onStateChangeTriggered = true; super.onStateChange(instanceName, statesInfo, changeContext); } } }
9,675
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMessage2.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.StringWriter; import java.util.Set; import java.util.UUID; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.apache.helix.Criteria; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.InstanceType; import org.apache.helix.PropertyKey; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.integration.common.ZkStandAloneCMTestBase; import org.apache.helix.manager.zk.DefaultSchedulerMessageHandlerFactory; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageState; import org.apache.helix.model.Message.MessageType; import org.testng.Assert; import org.testng.annotations.Test; public class TestSchedulerMessage2 extends ZkStandAloneCMTestBase { TestSchedulerMessage.TestMessagingHandlerFactory _factory = new TestSchedulerMessage.TestMessagingHandlerFactory(); @Test() public void testSchedulerMsg2() throws Exception { _factory._results.clear(); Thread.sleep(2000); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory( _factory.getMessageType(), _factory); manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); // Template for the individual message sent to each participant Message msg = new Message(_factory.getMessageType(), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("%"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); schedulerMessage.getRecord().setSimpleField("WAIT_ALL", "true"); Criteria cr2 = new Criteria(); cr2.setRecipientInstanceType(InstanceType.CONTROLLER); cr2.setInstanceName("*"); cr2.setSessionSpecific(false); schedulerMessage.getRecord().setSimpleField( DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE, "TestSchedulerMsg2"); TestSchedulerMessage.MockAsyncCallback callback = new TestSchedulerMessage.MockAsyncCallback(); manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1); String msgId = callback._message.getResultMap() .get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = helixDataAccessor.keyBuilder(); for (int i = 0; i < 10; i++) { Thread.sleep(200); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (statusUpdate.getMapFields().containsKey("Summary")) { break; } } Assert.assertEquals(_PARTITIONS, _factory._results.size()); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount") .equals("" + (_PARTITIONS * 3))); int messageResultCount = 0; for (String key : statusUpdate.getMapFields().keySet()) { if (key.startsWith("MessageResult ")) { messageResultCount++; } } Assert.assertEquals(messageResultCount, _PARTITIONS * 3); int count = 0; for (Set<String> val : _factory._results.values()) { count += val.size(); } Assert.assertEquals(count, _PARTITIONS * 3); } }
9,676
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestGroupCommitAddBackData.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.UUID; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.common.ZkTestBase; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.integration.task.WorkflowGenerator; import org.apache.helix.model.Message; 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 TestGroupCommitAddBackData extends ZkTestBase { private static Logger LOG = LoggerFactory.getLogger(TestGroupCommitAddBackData.class); private static final int START_PORT = 12918; private static final int DEFAULT_TIMEOUT = 30 * 1000; private HelixManager _manager; private final String CLASS_NAME = getShortClassName(); private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME; private MockParticipantManager _participant; @BeforeClass public void beforeClass() throws Exception { // Logger.getRootLogger().setLevel(Level.INFO); System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); // setup storage cluster _gSetupTool.addCluster(CLUSTER_NAME, true); String storageNodeName = PARTICIPANT_PREFIX + "_" + START_PORT; _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); _participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName); _participant.syncStart(); // create cluster manager _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); } @AfterClass public void afterClass() throws Exception { if (_participant != null && _participant.isConnected()) { _participant.syncStop(); } if (_manager != null && _manager.isConnected()) { _manager.disconnect(); } String namespace = "/" + CLUSTER_NAME; if (_gZkClient.exists(namespace)) { try { _gSetupTool.deleteCluster(CLUSTER_NAME); } catch (Exception ex) { System.err.println( "Failed to delete cluster " + CLUSTER_NAME + ", error: " + ex.getLocalizedMessage()); _gSetupTool.deleteCluster(CLUSTER_NAME); } } System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); } @Test public void testGroupCommitAddCurrentStateBack() throws InterruptedException { HelixDataAccessor accessor = _manager.getHelixDataAccessor(); Message initMessage = generateMessage("OFFLINE", "ONLINE"); accessor.setProperty( accessor.keyBuilder().message(_participant.getInstanceName(), initMessage.getMsgId()), initMessage); Assert.assertTrue(waitForMessageProcessed(accessor, initMessage.getMsgId())); Message toOffline = generateMessage("ONLINE", "OFFLINE"); accessor.setProperty( accessor.keyBuilder().message(_participant.getInstanceName(), toOffline.getMsgId()), toOffline); Assert.assertTrue(waitForMessageProcessed(accessor, toOffline.getMsgId())); // Consequential 10 messages for (int i = 0; i < 10; i++) { Message dropped = generateMessage("OFFLINE", "DROPPED"); accessor.setProperty( accessor.keyBuilder().message(_participant.getInstanceName(), dropped.getMsgId()), dropped); Assert.assertTrue(waitForMessageProcessed(accessor, dropped.getMsgId())); Assert.assertFalse(accessor.getBaseDataAccessor() .exists(accessor.keyBuilder().currentState(_participant.getInstanceName(), _participant.getSessionId(), WorkflowGenerator.DEFAULT_TGT_DB).getPath(), 0)); } } private Message generateMessage(String from, String to) { String uuid = UUID.randomUUID().toString(); Message message = new Message(Message.MessageType.STATE_TRANSITION, uuid); message.setSrcName("ADMIN"); message.setTgtName(_participant.getInstanceName()); message.setMsgState(Message.MessageState.NEW); message.setPartitionName("P"); message.setResourceName(WorkflowGenerator.DEFAULT_TGT_DB); message.setFromState(from); message.setToState(to); message.setTgtSessionId(_participant.getSessionId()); message.setSrcSessionId(_manager.getSessionId()); message.setStateModelDef("OnlineOffline"); message.setStateModelFactoryName("DEFAULT"); return message; } private boolean waitForMessageProcessed(HelixDataAccessor accessor, String messageId) throws InterruptedException { String path = accessor.keyBuilder().message(_participant.getInstanceName(), messageId).getPath(); long startTime = System.currentTimeMillis(); while (accessor.getBaseDataAccessor().exists(path, 0)) { if (System.currentTimeMillis() - startTime > DEFAULT_TIMEOUT) { return false; } Thread.sleep(200); } return true; } }
9,677
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PSingleTopState.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixDataAccessor; import org.apache.helix.NotificationContext; import org.apache.helix.TestHelper; import org.apache.helix.common.ZkTestBase; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.integration.DelayedTransitionBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.mock.participant.MockTransition; import org.apache.helix.model.BuiltInStateModelDefinitions; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.model.Message; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestP2PSingleTopState extends ZkTestBase { final String CLASS_NAME = getShortClassName(); final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME; static final int PARTICIPANT_NUMBER = 24; static final int PARTICIPANT_START_PORT = 12918; static final int DB_COUNT = 2; static final int PARTITION_NUMBER = 50; static final int REPLICA_NUMBER = 3; final String _controllerName = CONTROLLER_PREFIX + "_0"; List<MockParticipantManager> _participants = new ArrayList<>(); List<String> _instances = new ArrayList<>(); ClusterControllerManager _controller; ZkHelixClusterVerifier _clusterVerifier; ConfigAccessor _configAccessor; HelixDataAccessor _accessor; @BeforeClass public void beforeClass() { System.out .println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis())); // setup storage cluster _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < PARTICIPANT_NUMBER / 2; i++) { String instance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance); _instances.add(instance); } // start dummy participants for (int i = 0; i < PARTICIPANT_NUMBER / 2; i++) { MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _instances.get(i)); participant.setTransition(new DelayedTransitionBase(100)); participant.syncStart(); participant.setTransition(new TestTransition(participant.getInstanceName())); _participants.add(participant); } _configAccessor = new ConfigAccessor(_gZkClient); _accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor); enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true, 1000000); // enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, false); enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true); enableP2PInCluster(CLUSTER_NAME, _configAccessor, true); // start controller _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, _controllerName); _controller.syncStart(); for (int i = 0; i < DB_COUNT; i++) { createResourceWithDelayedRebalance(CLUSTER_NAME, "TestDB_" + i, BuiltInStateModelDefinitions.MasterSlave.name(), PARTITION_NUMBER, REPLICA_NUMBER, REPLICA_NUMBER - 1, 1000000L, CrushEdRebalanceStrategy.class.getName()); } _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); } @AfterClass public void afterClass() throws Exception { _controller.syncStop(); for (MockParticipantManager p : _participants) { p.syncStop(); } deleteCluster(CLUSTER_NAME); System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); } @Test public void testRollingUpgrade() throws InterruptedException { // rolling upgrade the cluster for (String ins : _instances) { System.out.println("Disable " + ins); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, ins, false); Assert.assertTrue(_clusterVerifier.verifyByPolling()); System.out.println("Enable " + ins); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, ins, true); Assert.assertTrue(_clusterVerifier.verifyByPolling()); } Assert.assertTrue(_clusterVerifier.verifyByPolling()); Assert.assertFalse(TestTransition.duplicatedPartitionsSnapshot.keys().hasMoreElements()); } @Test public void testAddInstances() throws InterruptedException { for (int i = PARTICIPANT_NUMBER / 2; i < PARTICIPANT_NUMBER; i++) { String instance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance); _instances.add(instance); MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _instances.get(i)); participant.setTransition(new DelayedTransitionBase(100)); participant.syncStart(); participant.setTransition(new TestTransition(participant.getInstanceName())); _participants.add(participant); Thread.sleep(100); } Assert.assertTrue(_clusterVerifier.verifyByPolling()); Assert.assertFalse(TestTransition.duplicatedPartitionsSnapshot.keys().hasMoreElements()); } static class TestTransition extends MockTransition { // resource.partition that having top state. static ConcurrentHashMap<String, Map<String, String>> duplicatedPartitionsSnapshot = new ConcurrentHashMap<>(); static ConcurrentHashMap<String, Map<String, String>> ExternalViews = new ConcurrentHashMap<>(); static AtomicLong totalToMaster = new AtomicLong(); static AtomicLong totalRelayMessage = new AtomicLong(); String _instanceName; TestTransition(String instanceName) { _instanceName = instanceName; } public void doTransition(Message message, NotificationContext context) { String to = message.getToState(); String resource = message.getResourceName(); String partition = message.getPartitionName(); String key = resource + "." + partition; if (to.equals(MasterSlaveSMD.States.MASTER.name())) { Map<String, String> mapFields = new HashMap<>(ExternalViews.get(key)); if (mapFields.values().contains(MasterSlaveSMD.States.MASTER.name())) { Map<String, String> newMapFile = new HashMap<>(mapFields); newMapFile.put(_instanceName, to); duplicatedPartitionsSnapshot.put(key, newMapFile); } totalToMaster.incrementAndGet(); if (message.isRelayMessage()) { totalRelayMessage.incrementAndGet(); } } ExternalViews.putIfAbsent(key, new ConcurrentHashMap<>()); if (to.equalsIgnoreCase("DROPPED")) { ExternalViews.get(key).remove(_instanceName); } else { ExternalViews.get(key).put(_instanceName, to); } } } }
9,678
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestBatchMessage.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.helix.HelixProperty.HelixPropertyAttribute; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.TestHelper; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.common.ZkTestBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.mock.participant.ErrTransition; import org.apache.helix.model.IdealState; import org.apache.helix.model.LiveInstance; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.tools.ClusterStateVerifier; import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier; import org.apache.helix.zookeeper.zkclient.IZkChildListener; import org.testng.Assert; import org.testng.annotations.Test; public class TestBatchMessage extends ZkTestBase { class TestZkChildListener implements IZkChildListener { int _maxNumberOfChildren = 0; @Override public void handleChildChange(String parentPath, List<String> currentChildren) { if (currentChildren == null) { return; } System.out.println(parentPath + " has " + currentChildren.size() + " messages"); if (currentChildren.size() > _maxNumberOfChildren) { _maxNumberOfChildren = currentChildren.size(); } } } @Test public void testBasic() throws Exception { // Logger.getRootLogger().setLevel(Level.INFO); String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; int n = 2; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port "localhost", // participant name prefix "TestDB", // resource name prefix 1, // resources 32, // partitions per resource n, // number of nodes 2, // replicas "MasterSlave", true); // do rebalance // enable batch message ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0")); idealState.setBatchMessageMode(true); accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState); // register a message listener so we know how many message generated TestZkChildListener listener = new TestZkChildListener(); _gZkClient.subscribeChildChanges(keyBuilder.messages("localhost_12918").getPath(), listener); ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0"); controller.syncStart(); // start participants MockParticipantManager[] participants = new MockParticipantManager[n]; for (int i = 0; i < n; i++) { String instanceName = "localhost_" + (12918 + i); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].syncStart(); } BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName); try { boolean result = ClusterStateVerifier .verifyByZkCallback(verifier); Assert.assertTrue(result); // Change to three is because there is an extra factory registered // So one extra NO_OP message send Assert.assertTrue(listener._maxNumberOfChildren <= 3, "Should get no more than 2 messages (O->S and S->M)"); } finally { verifier.close(); } // clean up // wait for all zk callbacks done controller.syncStop(); for (int i = 0; i < n; i++) { participants[i].syncStop(); } deleteCluster(clusterName); System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } // a non-batch-message run followed by a batch-message-enabled run @Test public void testChangeBatchMessageMode() throws Exception { // Logger.getRootLogger().setLevel(Level.INFO); String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; int n = 2; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port "localhost", // participant name prefix "TestDB", // resource name prefix 1, // resources 32, // partitions per resource n, // number of nodes 2, // replicas "MasterSlave", true); // do rebalance ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0"); controller.syncStart(); // start participants MockParticipantManager[] participants = new MockParticipantManager[n]; for (int i = 0; i < n; i++) { String instanceName = "localhost_" + (12918 + i); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].syncStart(); } BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName); try { boolean result = ClusterStateVerifier.verifyByZkCallback(verifier); Assert.assertTrue(result); } finally { verifier.close(); } // stop all participants for (int i = 0; i < n; i++) { participants[i].syncStop(); } // enable batch message ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0")); idealState.setBatchMessageMode(true); accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState); // registry a message listener so we know how many message generated TestZkChildListener listener = new TestZkChildListener(); _gZkClient.subscribeChildChanges(keyBuilder.messages("localhost_12918").getPath(), listener); // restart all participants for (int i = 0; i < n; i++) { String instanceName = "localhost_" + (12918 + i); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].syncStart(); } verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName); try { boolean result = ClusterStateVerifier .verifyByZkCallback(verifier); Assert.assertTrue(result); // Change to three is because there is an extra factory registered // So one extra NO_OP message send Assert.assertTrue(listener._maxNumberOfChildren <= 3, "Should get no more than 2 messages (O->S and S->M)"); } finally { verifier.close(); } // clean up // wait for all zk callbacks done controller.syncStop(); for (int i = 0; i < n; i++) { participants[i].syncStop(); } deleteCluster(clusterName); System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSubMsgExecutionFail() throws Exception { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; final int n = 5; MockParticipantManager[] participants = new MockParticipantManager[n]; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, // resource# 6, // partition# n, // nodes# 3, // replicas# "MasterSlave", true); // enable batch message ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor); Builder keyBuilder = accessor.keyBuilder(); IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0")); idealState.setBatchMessageMode(true); accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState); // get MASTER for errPartition String errPartition = "TestDB0_0"; String masterOfPartition0 = null; for (Map.Entry<String, String> entry : idealState.getInstanceStateMap(errPartition).entrySet()) { if (entry.getValue().equals("MASTER")) { masterOfPartition0 = entry.getKey(); break; } } Assert.assertNotNull(masterOfPartition0); ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName); controller.syncStart(); for (int i = 0; i < n; i++) { String instanceName = "localhost_" + (12918 + i); if (instanceName.equals(masterOfPartition0)) { Map<String, Set<String>> errPartitions = new HashMap<String, Set<String>>(); errPartitions.put("SLAVE-MASTER", TestHelper.setOf("TestDB0_0")); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].setTransition(new ErrTransition(errPartitions)); } else { participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); } participants[i].syncStart(); } Map<String, Map<String, String>> errStates = new HashMap<String, Map<String, String>>(); errStates.put("TestDB0", new HashMap<String, String>()); errStates.get("TestDB0").put(errPartition, masterOfPartition0); BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier( ZK_ADDR, clusterName, errStates); try { boolean result = ClusterStateVerifier.verifyByPolling( verifier); Assert.assertTrue(result); } finally { verifier.close(); } Map<String, Set<String>> errorStateMap = new HashMap<String, Set<String>>(); errorStateMap.put(errPartition, TestHelper.setOf(masterOfPartition0)); // verify "TestDB0_0", masterOfPartition0 is in ERROR state TestHelper.verifyState(clusterName, ZK_ADDR, errorStateMap, "ERROR"); // clean up controller.syncStop(); for (int i = 0; i < n; i++) { participants[i].syncStop(); } deleteCluster(clusterName); System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } @Test public void testParticipantIncompatibleWithBatchMsg() throws Exception { // Logger.getRootLogger().setLevel(Level.INFO); String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; int n = 2; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port "localhost", // participant name prefix "TestDB", // resource name prefix 1, // resources 32, // partitions per resource n, // number of nodes 2, // replicas "MasterSlave", true); // do rebalance // enable batch message // --addResourceProperty <clusterName resourceName propertyName propertyValue> ClusterSetup.processCommandLineArgs(new String[] { "--zkSvr", ZK_ADDR, "--addResourceProperty", clusterName, "TestDB0", HelixPropertyAttribute.BATCH_MESSAGE_MODE.toString(), "true" }); ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); // register a message listener so we know how many message generated TestZkChildListener listener = new TestZkChildListener(); _gZkClient.subscribeChildChanges(keyBuilder.messages("localhost_12918").getPath(), listener); ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0"); controller.syncStart(); // pause controller // --enableCluster <clusterName true/false> ClusterSetup.processCommandLineArgs(new String[] { "--zkSvr", ZK_ADDR, "--enableCluster", clusterName, "false" }); // start participants MockParticipantManager[] participants = new MockParticipantManager[n]; for (int i = 0; i < n; i++) { String instanceName = "localhost_" + (12918 + i); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].syncStart(); } // change localhost_12918 version to 0.5, so batch-message-mode will be ignored LiveInstance liveInstance = accessor.getProperty(keyBuilder.liveInstance("localhost_12918")); liveInstance.setHelixVersion("0.5"); accessor.setProperty(keyBuilder.liveInstance("localhost_12918"), liveInstance); // resume controller // --enableCluster <clusterName true/false> ClusterSetup.processCommandLineArgs(new String[] { "--zkSvr", ZK_ADDR, "--enableCluster", clusterName, "true" }); BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName); try { boolean result = ClusterStateVerifier .verifyByZkCallback(verifier); Assert.assertTrue(result); Assert.assertTrue(listener._maxNumberOfChildren > 16, "Should see more than 16 messages at the same time (32 O->S and 32 S->M)"); } finally { verifier.close(); } // clean up // wait for all zk callbacks done controller.syncStop(); for (int i = 0; i < n; i++) { participants[i].syncStop(); } deleteCluster(clusterName); System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } }
9,679
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestCrossClusterMessagingService.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.UUID; import org.apache.helix.Criteria; import org.apache.helix.Criteria.DataSource; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.messaging.AsyncCallback; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageState; import org.apache.helix.model.Message.MessageType; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestCrossClusterMessagingService extends TestMessagingService { private final String ADMIN_CLUSTER_NAME = "ADMIN_" + CLUSTER_NAME; private ClusterControllerManager _adminController; private String _hostSrc; @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); // setup the admin cluster for sending cross cluster messages _gSetupTool.addCluster(ADMIN_CLUSTER_NAME, true); // start controller String controllerName = CONTROLLER_PREFIX + "_1"; _hostSrc = controllerName; _adminController = new ClusterControllerManager(ZK_ADDR, ADMIN_CLUSTER_NAME, controllerName); _adminController.syncStart(); ZkHelixClusterVerifier adminClusterVerifier = new BestPossibleExternalViewVerifier.Builder(ADMIN_CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(adminClusterVerifier.verifyByPolling()); } @AfterClass public void afterClass() throws Exception { if (_adminController != null && _adminController.isConnected()) { _adminController.syncStop(); } deleteCluster(ADMIN_CLUSTER_NAME); super.afterClass(); } @Test() public void TestMessageSimpleSend() throws Exception { String hostDest = "localhost_" + (START_PORT + 1); TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); String msgId = new UUID(123, 456).toString(); Message msg = new Message(factory.getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(_hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setClusterName(CLUSTER_NAME); int nMsgs = _adminController.getMessagingService().send(cr, msg); AssertJUnit.assertEquals(nMsgs, 1); Thread.sleep(2500); AssertJUnit.assertTrue(TestMessagingHandlerFactory._processedMsgIds.contains(para)); cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setDataSource(DataSource.IDEALSTATES); cr.setClusterName(CLUSTER_NAME); // nMsgs = _startCMResultMap.get(hostSrc)._manager.getMessagingService().send(cr, msg); nMsgs = _adminController.getMessagingService().send(cr, msg); AssertJUnit.assertEquals(nMsgs, 1); Thread.sleep(2500); AssertJUnit.assertTrue(TestMessagingHandlerFactory._processedMsgIds.contains(para)); } @Test() public void TestMessageSimpleSendReceiveAsync() throws Exception { String hostDest = "localhost_" + (START_PORT + 1); TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); _participants[0].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); String msgId = new UUID(123, 456).toString(); Message msg = new Message(factory.getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(_hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setClusterName(CLUSTER_NAME); TestAsyncCallback callback = new TestAsyncCallback(60000); _adminController.getMessagingService().send(cr, msg, callback, 60000); Thread.sleep(2000); AssertJUnit.assertTrue(TestAsyncCallback._replyedMessageContents.contains("TestReplyMessage")); AssertJUnit.assertEquals(callback.getMessageReplied().size(), 1); TestAsyncCallback callback2 = new TestAsyncCallback(500); _adminController.getMessagingService().send(cr, msg, callback2, 500); Thread.sleep(3000); AssertJUnit.assertTrue(callback2.isTimedOut()); cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setDataSource(DataSource.IDEALSTATES); cr.setClusterName(CLUSTER_NAME); callback = new TestAsyncCallback(60000); _adminController.getMessagingService().send(cr, msg, callback, 60000); Thread.sleep(2000); AssertJUnit.assertTrue(TestAsyncCallback._replyedMessageContents.contains("TestReplyMessage")); AssertJUnit.assertEquals(callback.getMessageReplied().size(), 1); callback2 = new TestAsyncCallback(500); _adminController.getMessagingService().send(cr, msg, callback2, 500); Thread.sleep(3000); AssertJUnit.assertTrue(callback2.isTimedOut()); } @Test() public void TestBlockingSendReceive() { String hostDest = "localhost_" + (START_PORT + 1); TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); String msgId = new UUID(123, 456).toString(); Message msg = new Message(factory.getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(_hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setClusterName(CLUSTER_NAME); AsyncCallback asyncCallback = new MockAsyncCallback(); int messagesSent = _adminController.getMessagingService().sendAndWait(cr, msg, asyncCallback, 60000); AssertJUnit.assertEquals( asyncCallback.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage"), "TestReplyMessage"); AssertJUnit.assertEquals(asyncCallback.getMessageReplied().size(), 1); AsyncCallback asyncCallback2 = new MockAsyncCallback(); messagesSent = _adminController.getMessagingService().sendAndWait(cr, msg, asyncCallback2, 500); AssertJUnit.assertTrue(asyncCallback2.isTimedOut()); } @Test() public void TestMultiMessageCriteria() { for (int i = 0; i < NODE_NR; i++) { TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[i].getMessagingService() .registerMessageHandlerFactory(factory.getMessageTypes(), factory); } String msgId = new UUID(123, 456).toString(); Message msg = new Message(new TestMessagingHandlerFactory().getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(_hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName("%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setClusterName(CLUSTER_NAME); AsyncCallback callback1 = new MockAsyncCallback(); int messageSent1 = _adminController.getMessagingService().sendAndWait(cr, msg, callback1, 10000); AssertJUnit.assertEquals( callback1.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage"), "TestReplyMessage"); AssertJUnit.assertEquals(NODE_NR, callback1.getMessageReplied().size()); AsyncCallback callback2 = new MockAsyncCallback(); int messageSent2 = _adminController.getMessagingService().sendAndWait(cr, msg, callback2, 500); AssertJUnit.assertTrue(callback2.isTimedOut()); cr.setPartition("TestDB_17"); AsyncCallback callback3 = new MockAsyncCallback(); int messageSent3 = _adminController.getMessagingService().sendAndWait(cr, msg, callback3, 10000); AssertJUnit.assertEquals(_replica, callback3.getMessageReplied().size()); cr.setPartition("TestDB_15"); AsyncCallback callback4 = new MockAsyncCallback(); int messageSent4 = _adminController.getMessagingService().sendAndWait(cr, msg, callback4, 10000); AssertJUnit.assertEquals(_replica, callback4.getMessageReplied().size()); cr.setPartitionState("SLAVE"); AsyncCallback callback5 = new MockAsyncCallback(); int messageSent5 = _adminController.getMessagingService().sendAndWait(cr, msg, callback5, 10000); AssertJUnit.assertEquals(_replica - 1, callback5.getMessageReplied().size()); cr.setDataSource(DataSource.IDEALSTATES); AsyncCallback callback6 = new MockAsyncCallback(); int messageSent6 = _adminController.getMessagingService().sendAndWait(cr, msg, callback6, 10000); AssertJUnit.assertEquals(_replica - 1, callback6.getMessageReplied().size()); } @Test() public void TestControllerMessage() { for (int i = 0; i < NODE_NR; i++) { TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[i].getMessagingService() .registerMessageHandlerFactory(factory.getMessageTypes(), factory); } String msgId = new UUID(123, 456).toString(); Message msg = new Message(MessageType.CONTROLLER_MSG, msgId); msg.setMsgId(msgId); msg.setSrcName(_hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName("*"); cr.setRecipientInstanceType(InstanceType.CONTROLLER); cr.setSessionSpecific(false); cr.setClusterName(CLUSTER_NAME); AsyncCallback callback1 = new MockAsyncCallback(); int messagesSent = _adminController.getMessagingService().sendAndWait(cr, msg, callback1, 10000); AssertJUnit.assertTrue(callback1.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult") .contains(_hostSrc)); AssertJUnit.assertEquals(callback1.getMessageReplied().size(), 1); msgId = UUID.randomUUID().toString(); msg.setMsgId(msgId); cr.setPartition("TestDB_17"); AsyncCallback callback2 = new MockAsyncCallback(); messagesSent = _adminController.getMessagingService().sendAndWait(cr, msg, callback2, 10000); AssertJUnit.assertTrue(callback2.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult") .contains(_hostSrc)); AssertJUnit.assertEquals(callback2.getMessageReplied().size(), 1); msgId = UUID.randomUUID().toString(); msg.setMsgId(msgId); cr.setPartitionState("SLAVE"); AsyncCallback callback3 = new MockAsyncCallback(); messagesSent = _adminController.getMessagingService().sendAndWait(cr, msg, callback3, 10000); AssertJUnit.assertTrue(callback3.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult") .contains(_hostSrc)); AssertJUnit.assertEquals(callback3.getMessageReplied().size(), 1); } @Test(enabled = false) public void sendSelfMsg() { // Override the test defined in parent class. } }
9,680
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMessage.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CountDownLatch; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; import org.apache.helix.Criteria; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.InstanceType; import org.apache.helix.NotificationContext; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.TestHelper; import org.apache.helix.integration.common.ZkStandAloneCMTestBase; import org.apache.helix.manager.zk.DefaultSchedulerMessageHandlerFactory; import org.apache.helix.messaging.AsyncCallback; import org.apache.helix.messaging.handling.HelixTaskResult; import org.apache.helix.messaging.handling.MessageHandler; import org.apache.helix.messaging.handling.MultiTypeMessageHandlerFactory; import org.apache.helix.model.ClusterConstraints.ConstraintType; import org.apache.helix.model.ConstraintItem; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageState; import org.apache.helix.model.Message.MessageType; import org.apache.helix.model.StatusUpdate; import org.apache.helix.monitoring.ZKPathDataDumpTask; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.testng.Assert; import org.testng.annotations.Test; public class TestSchedulerMessage extends ZkStandAloneCMTestBase { public static class MockAsyncCallback extends AsyncCallback { Message _message; MockAsyncCallback() { } @Override public void onTimeOut() { // TODO Auto-generated method stub } @Override public void onReplyMessage(Message message) { _message = message; } } private TestMessagingHandlerFactory _factory = new TestMessagingHandlerFactory(); public static class TestMessagingHandlerFactory implements MultiTypeMessageHandlerFactory { final Map<String, Set<String>> _results = new ConcurrentHashMap<>(); @Override public MessageHandler createHandler(Message message, NotificationContext context) { return new TestMessagingHandler(message, context); } @Override public List<String> getMessageTypes() { return ImmutableList.of("TestParticipant"); } @Override public void reset() { // TODO Auto-generated method stub } public class TestMessagingHandler extends MessageHandler { TestMessagingHandler(Message message, NotificationContext context) { super(message, context); // TODO Auto-generated constructor stub } @Override public HelixTaskResult handleMessage() { HelixTaskResult result = new HelixTaskResult(); result.setSuccess(true); result.getTaskResultMap().put("Message", _message.getMsgId()); synchronized (_results) { if (!_results.containsKey(_message.getPartitionName())) { _results.put(_message.getPartitionName(), new ConcurrentSkipListSet<>()); } } _results.get(_message.getPartitionName()).add(_message.getMsgId()); return result; } @Override public void onError(Exception e, ErrorCode code, ErrorType type) { // TODO Auto-generated method stub } } } public static class TestMessagingHandlerFactoryLatch implements MultiTypeMessageHandlerFactory { volatile CountDownLatch _latch = new CountDownLatch(1); int _messageCount = 0; final Map<String, Set<String>> _results = new ConcurrentHashMap<>(); @Override public synchronized MessageHandler createHandler(Message message, NotificationContext context) { _messageCount++; return new TestMessagingHandlerLatch(message, context); } synchronized void signal() { _latch.countDown(); _latch = new CountDownLatch(1); } @Override public List<String> getMessageTypes() { return ImmutableList.of("TestMessagingHandlerLatch"); } @Override public void reset() { // TODO Auto-generated method stub } public class TestMessagingHandlerLatch extends MessageHandler { TestMessagingHandlerLatch(Message message, NotificationContext context) { super(message, context); // TODO Auto-generated constructor stub } @Override public HelixTaskResult handleMessage() throws InterruptedException { _latch.await(); HelixTaskResult result = new HelixTaskResult(); result.setSuccess(true); result.getTaskResultMap().put("Message", _message.getMsgId()); String destName = _message.getTgtName(); synchronized (_results) { if (!_results.containsKey(_message.getPartitionName())) { _results.put(_message.getPartitionName(), new ConcurrentSkipListSet<>()); } } _results.get(_message.getPartitionName()).add(destName); return result; } @Override public void onError(Exception e, ErrorCode code, ErrorType type) { // TODO Auto-generated method stub } } } @Test(dependsOnMethods = "testSchedulerZeroMsg") public void testSchedulerMsg() throws Exception { _factory._results.clear(); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory(_factory.getMessageTypes(), _factory); manager = _participants[i]; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); // Template for the individual message sent to each participant Message msg = new Message(_factory.getMessageTypes().get(0), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("%"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); Builder keyBuilder = helixDataAccessor.keyBuilder(); helixDataAccessor.createControllerMessage(schedulerMessage); Assert.assertTrue(TestHelper.verify(() -> _PARTITIONS == _factory._results.size(), TestHelper.WAIT_DURATION)); Assert.assertEquals(_PARTITIONS, _factory._results.size()); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), schedulerMessage.getMsgId()); Assert.assertTrue(TestHelper.verify(() -> { ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); try { if (_PARTITIONS * 3 != Integer.parseInt(statusUpdate.getMapField("SentMessageCount").get("MessageCount"))) { return false; } } catch (Exception ex) { return false; } int messageResultCount = 0; for (String key : statusUpdate.getMapFields().keySet()) { if (key.startsWith("MessageResult ")) { messageResultCount++; if (statusUpdate.getMapField(key).size() <= 1) { return false; } } } if (messageResultCount != _PARTITIONS * 3) { return false; } int count = 0; for (Set<String> val : _factory._results.values()) { count += val.size(); } return count == _PARTITIONS * 3; }, TestHelper.WAIT_DURATION)); // test the ZkPathDataDumpTask String controllerStatusPath = PropertyPathBuilder.controllerStatusUpdate(manager.getClusterName()); List<String> subPaths = _gZkClient.getChildren(controllerStatusPath); Assert.assertTrue(subPaths.size() > 0); for (String subPath : subPaths) { String nextPath = controllerStatusPath + "/" + subPath; List<String> subsubPaths = _gZkClient.getChildren(nextPath); Assert.assertTrue(subsubPaths.size() > 0); } String instanceStatusPath = PropertyPathBuilder.instanceStatusUpdate(manager.getClusterName(), "localhost_" + (START_PORT)); subPaths = _gZkClient.getChildren(instanceStatusPath); Assert.assertEquals(subPaths.size(), 0); for (String subPath : subPaths) { String nextPath = instanceStatusPath + "/" + subPath; List<String> subsubPaths = _gZkClient.getChildren(nextPath); Assert.assertTrue(subsubPaths.size() > 0); for (String subsubPath : subsubPaths) { String nextnextPath = nextPath + "/" + subsubPath; Assert.assertTrue(_gZkClient.getChildren(nextnextPath).size() > 0); } } Thread.sleep(3000); ZKPathDataDumpTask dumpTask = new ZKPathDataDumpTask(manager, 0L, 0L, Integer.MAX_VALUE); dumpTask.run(); subPaths = _gZkClient.getChildren(controllerStatusPath); Assert.assertTrue(subPaths.size() > 0); for (String subPath : subPaths) { String nextPath = controllerStatusPath + "/" + subPath; List<String> subsubPaths = _gZkClient.getChildren(nextPath); Assert.assertEquals(subsubPaths.size(), 0); } subPaths = _gZkClient.getChildren(instanceStatusPath); Assert.assertEquals(subPaths.size(), 0); for (String subPath : subPaths) { String nextPath = instanceStatusPath + "/" + subPath; List<String> subsubPaths = _gZkClient.getChildren(nextPath); Assert.assertTrue(subsubPaths.size() > 0); for (String subsubPath : subsubPaths) { String nextnextPath = nextPath + "/" + subsubPath; Assert.assertEquals(_gZkClient.getChildren(nextnextPath).size(), 0); } } } @Test public void testSchedulerZeroMsg() throws Exception { _factory._results.clear(); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory(_factory.getMessageTypes(), _factory); manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); // Template for the individual message sent to each participant Message msg = new Message(_factory.getMessageTypes().get(0), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_DOESNOTEXIST"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("%"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); Builder keyBuilder = helixDataAccessor.keyBuilder(); PropertyKey controllerMessageKey = keyBuilder.controllerMessage(schedulerMessage.getMsgId()); helixDataAccessor.setProperty(controllerMessageKey, schedulerMessage); Thread.sleep(3000); Assert.assertEquals(0, _factory._results.size()); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), schedulerMessage.getMsgId()); // Need to wait until record is ready Assert.assertTrue(TestHelper.verify(() -> { StatusUpdate update = helixDataAccessor.getProperty(controllerTaskStatus); return update != null && update.getRecord().getMapField("SentMessageCount") != null; }, 10 * 1000)); // Ensure the records remains to be zero ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); Assert.assertEquals(statusUpdate.getMapField("SentMessageCount").get("MessageCount"), "0"); int count = 0; for (Set<String> val : _factory._results.values()) { count += val.size(); } Assert.assertEquals(count, 0); } @Test(dependsOnMethods = "testSchedulerMsg") public void testSchedulerMsg3() throws Exception { _factory._results.clear(); Thread.sleep(2000); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory(_factory.getMessageTypes(), _factory); manager = _participants[i]; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); // Template for the individual message sent to each participant Message msg = new Message(_factory.getMessageTypes().get(0), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("%"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); schedulerMessage.getRecord().setSimpleField("WAIT_ALL", "true"); schedulerMessage.getRecord() .setSimpleField(DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE, "TestSchedulerMsg3"); Criteria cr2 = new Criteria(); cr2.setRecipientInstanceType(InstanceType.CONTROLLER); cr2.setInstanceName("*"); cr2.setSessionSpecific(false); MockAsyncCallback callback; cr.setInstanceName("localhost_%"); mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); sw = new StringWriter(); mapper.writeValue(sw, cr); crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); for (int i = 0; i < 4; i++) { callback = new MockAsyncCallback(); cr.setInstanceName("localhost_" + (START_PORT + i)); mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); sw = new StringWriter(); mapper.writeValue(sw, cr); schedulerMessage.setMsgId(UUID.randomUUID().toString()); crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1); String msgId = callback._message.getResultMap().get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); Builder keyBuilder = helixDataAccessor.keyBuilder(); // Wait until all sub messages to be processed PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); int instanceOrder = i; Assert.assertTrue(TestHelper.verify(() -> { ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (!statusUpdate.getMapFields().containsKey("Summary")) { return false; } try { if (_PARTITIONS * 3 / 5 != Integer.parseInt( statusUpdate.getMapField("SentMessageCount").get("MessageCount"))) { return false; } } catch (Exception ex) { return false; } int messageResultCount = 0; for (String key : statusUpdate.getMapFields().keySet()) { if (key.startsWith("MessageResult")) { messageResultCount++; } } if (messageResultCount != _PARTITIONS * 3 / 5) { return false; } int count = 0; for (Set<String> val : _factory._results.values()) { count += val.size(); } return count == _PARTITIONS * 3 / 5 * (instanceOrder + 1); }, TestHelper.WAIT_DURATION)); } } @Test(dependsOnMethods = "testSchedulerMsg3") public void testSchedulerMsg4() throws Exception { _factory._results.clear(); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory(_factory.getMessageTypes(), _factory); manager = _participants[i]; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); // Template for the individual message sent to each participant Message msg = new Message(_factory.getMessageTypes().get(0), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("TestDB"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); schedulerMessage.getRecord().setSimpleField("WAIT_ALL", "true"); schedulerMessage.getRecord() .setSimpleField(DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE, "TestSchedulerMsg4"); Criteria cr2 = new Criteria(); cr2.setRecipientInstanceType(InstanceType.CONTROLLER); cr2.setInstanceName("*"); cr2.setSessionSpecific(false); Map<String, String> constraints = new TreeMap<>(); constraints.put("MESSAGE_TYPE", "STATE_TRANSITION"); constraints.put("TRANSITION", "OFFLINE-COMPLETED"); constraints.put("CONSTRAINT_VALUE", "1"); constraints.put("INSTANCE", ".*"); manager.getClusterManagmentTool() .setConstraint(manager.getClusterName(), ConstraintType.MESSAGE_CONSTRAINT, "constraint1", new ConstraintItem(constraints)); MockAsyncCallback callback = new MockAsyncCallback(); cr.setInstanceName("localhost_%"); mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); sw = new StringWriter(); mapper.writeValue(sw, cr); crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1); String msgIdPrime = callback._message.getResultMap().get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); Builder keyBuilder = helixDataAccessor.keyBuilder(); ArrayList<String> msgIds = new ArrayList<>(); for (int i = 0; i < NODE_NR; i++) { callback = new MockAsyncCallback(); cr.setInstanceName("localhost_" + (START_PORT + i)); mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); sw = new StringWriter(); mapper.writeValue(sw, cr); schedulerMessage.setMsgId(UUID.randomUUID().toString()); crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1); String msgId = callback._message.getResultMap().get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID); msgIds.add(msgId); } for (int i = 0; i < NODE_NR; i++) { String msgId = msgIds.get(i); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); // Wait until all sub messages to be processed Assert.assertTrue(TestHelper.verify(() -> { ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (!statusUpdate.getMapFields().containsKey("Summary")) { return false; } try { if (_PARTITIONS * 3 / 5 != Integer.parseInt( statusUpdate.getMapField("SentMessageCount").get("MessageCount"))) { return false; } } catch (Exception ex) { return false; } int messageResultCount = 0; for (String key : statusUpdate.getMapFields().keySet()) { if (key.startsWith("MessageResult")) { messageResultCount++; } } return messageResultCount == _PARTITIONS * 3 / 5; }, TestHelper.WAIT_DURATION)); } // Wait until the main message to be processed PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgIdPrime); Assert.assertTrue(TestHelper.verify(() -> { ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (!statusUpdate.getMapFields().containsKey("Summary")) { return false; } int count = 0; for (Set<String> val : _factory._results.values()) { count += val.size(); } return count == _PARTITIONS * 3 * 2; }, TestHelper.WAIT_DURATION)); } }
9,681
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PNoDuplicatedMessage.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.helix.ClusterMessagingService; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.InstanceType; import org.apache.helix.TestHelper; import org.apache.helix.common.ZkTestBase; import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider; import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy; import org.apache.helix.integration.DelayedTransitionBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.messaging.DefaultMessagingService; import org.apache.helix.messaging.handling.HelixTaskExecutor; import org.apache.helix.messaging.handling.MessageHandlerFactory; import org.apache.helix.messaging.handling.MockHelixTaskExecutor; import org.apache.helix.model.BuiltInStateModelDefinitions; import org.apache.helix.model.CurrentState; import org.apache.helix.model.LiveInstance; import org.apache.helix.monitoring.mbeans.MessageQueueMonitor; import org.apache.helix.monitoring.mbeans.ParticipantStatusMonitor; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestP2PNoDuplicatedMessage extends ZkTestBase { private static Logger logger = LoggerFactory.getLogger(TestP2PNoDuplicatedMessage.class); final String CLASS_NAME = getShortClassName(); final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME; static final int PARTICIPANT_NUMBER = 10; static final int PARTICIPANT_START_PORT = 12918; static final int DB_COUNT = 2; static final int PARTITION_NUMBER = 100; static final int REPLICA_NUMBER = 3; final String _controllerName = CONTROLLER_PREFIX + "_0"; List<MockParticipantManager> _participants = new ArrayList<>(); List<String> _instances = new ArrayList<>(); ClusterControllerManager _controller; ZkHelixClusterVerifier _clusterVerifier; ConfigAccessor _configAccessor; HelixDataAccessor _accessor; @BeforeClass public void beforeClass() { System.out.println( "START " + getShortClassName() + " at " + new Date(System.currentTimeMillis())); // setup storage cluster _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < PARTICIPANT_NUMBER; i++) { String instance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance); _instances.add(instance); } // start dummy participants for (int i = 0; i < PARTICIPANT_NUMBER; i++) { MockParticipantManager participant = new TestParticipantManager(ZK_ADDR, CLUSTER_NAME, _instances.get(i)); participant.setTransition(new DelayedTransitionBase(100)); participant.syncStart(); _participants.add(participant); } enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true); enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true); for (int i = 0; i < DB_COUNT; i++) { createResourceWithDelayedRebalance(CLUSTER_NAME, "TestDB_" + i, BuiltInStateModelDefinitions.MasterSlave.name(), PARTITION_NUMBER, REPLICA_NUMBER, REPLICA_NUMBER - 1, 1000000L, CrushEdRebalanceStrategy.class.getName()); } // start controller _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, _controllerName); _controller.syncStart(); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); _configAccessor = new ConfigAccessor(_gZkClient); _accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor); } @AfterClass public void afterClass() throws Exception { _controller.syncStop(); for (MockParticipantManager p : _participants) { p.syncStop(); } deleteCluster(CLUSTER_NAME); System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); } @Test public void testP2PStateTransitionDisabled() { enableP2PInCluster(CLUSTER_NAME, _configAccessor, false); MockHelixTaskExecutor.resetStats(); // rolling upgrade the cluster for (String ins : _instances) { _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, ins, false); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PDisabled(); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, ins, true); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PDisabled(); } Assert.assertEquals(MockHelixTaskExecutor.duplicatedMessagesInProgress, 0, "There are duplicated transition messages sent while participant is handling the state-transition!"); Assert.assertEquals(MockHelixTaskExecutor.duplicatedMessages, 0, "There are duplicated transition messages sent at same time!"); } @Test (dependsOnMethods = {"testP2PStateTransitionDisabled"}) public void testP2PStateTransitionEnabled() throws Exception { enableP2PInCluster(CLUSTER_NAME, _configAccessor, true); long startTime = System.currentTimeMillis(); MockHelixTaskExecutor.resetStats(); // rolling upgrade the cluster for (String ins : _instances) { verifyP2P(startTime, ins, false); verifyP2P(startTime, ins, true); } Assert.assertEquals(MockHelixTaskExecutor.duplicatedMessagesInProgress, 0, "There are duplicated transition messages sent while participant is handling the state-transition!"); Assert.assertEquals(MockHelixTaskExecutor.duplicatedMessages, 0, "There are duplicated transition messages sent at same time!"); } private void verifyP2P(long startTime, String instance, boolean enabled) throws Exception { _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, instance, enabled); Assert.assertTrue(_clusterVerifier.verifyByPolling()); Assert.assertTrue(TestHelper.verify(() -> { total = 0; p2pTriggered = 0; verifyP2PEnabled(startTime); return total == p2pTriggered; }, TestHelper.WAIT_DURATION), "Number of successful p2p transitions when disable instance " + instance + ": " + p2pTriggered + " , expect: " + total); Thread.sleep(5000); } private void verifyP2PDisabled() { ResourceControllerDataProvider dataCache = new ResourceControllerDataProvider(CLUSTER_NAME); dataCache.refresh(_accessor); Map<String, LiveInstance> liveInstanceMap = dataCache.getLiveInstances(); for (LiveInstance instance : liveInstanceMap.values()) { Map<String, CurrentState> currentStateMap = dataCache.getCurrentState(instance.getInstanceName(), instance.getEphemeralOwner()); Assert.assertNotNull(currentStateMap); for (CurrentState currentState : currentStateMap.values()) { for (String partition : currentState.getPartitionStateMap().keySet()) { String state = currentState.getState(partition); if (state.equalsIgnoreCase("MASTER")) { String triggerHost = currentState.getTriggerHost(partition); Assert.assertEquals(triggerHost, _controllerName, state + " of " + partition + " on " + instance.getInstanceName() + " was triggered by " + triggerHost); } } } } } static int total = 0; static int p2pTriggered = 0; private void verifyP2PEnabled(long startTime) { ResourceControllerDataProvider dataCache = new ResourceControllerDataProvider(CLUSTER_NAME); dataCache.refresh(_accessor); Map<String, LiveInstance> liveInstanceMap = dataCache.getLiveInstances(); for (LiveInstance instance : liveInstanceMap.values()) { Map<String, CurrentState> currentStateMap = dataCache.getCurrentState(instance.getInstanceName(), instance.getEphemeralOwner()); Assert.assertNotNull(currentStateMap); for (CurrentState currentState : currentStateMap.values()) { for (String partition : currentState.getPartitionStateMap().keySet()) { String state = currentState.getState(partition); long start = currentState.getStartTime(partition); if (state.equalsIgnoreCase("MASTER") && start > startTime) { String triggerHost = currentState.getTriggerHost(partition); if (!triggerHost.equals(_controllerName)) { p2pTriggered ++; } total ++; } } } } } static class TestParticipantManager extends MockParticipantManager { private final DefaultMessagingService _messagingService; public TestParticipantManager(String zkAddr, String clusterName, String instanceName) { super(zkAddr, clusterName, instanceName); _messagingService = new MockMessagingService(this); } @Override public ClusterMessagingService getMessagingService() { // The caller can register message handler factories on messaging service before the // helix manager is connected. Thus we do not do connected check here. return _messagingService; } @Override public void finalize() { super.finalize(); } } static class MockMessagingService extends DefaultMessagingService { private final HelixTaskExecutor _taskExecutor; ConcurrentHashMap<String, MessageHandlerFactory> _messageHandlerFactoriestobeAdded = new ConcurrentHashMap<>(); private final HelixManager _manager; public MockMessagingService(HelixManager manager) { super(manager); _manager = manager; boolean isParticipant = false; if (manager.getInstanceType() == InstanceType.PARTICIPANT || manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) { isParticipant = true; } _taskExecutor = new MockHelixTaskExecutor( new ParticipantStatusMonitor(isParticipant, manager.getInstanceName()), new MessageQueueMonitor(manager.getClusterName(), manager.getInstanceName())); } @Override public synchronized void registerMessageHandlerFactory(String type, MessageHandlerFactory factory) { registerMessageHandlerFactory(Collections.singletonList(type), factory); } @Override public synchronized void registerMessageHandlerFactory(List<String> types, MessageHandlerFactory factory) { if (_manager.isConnected()) { for (String type : types) { registerMessageHandlerFactoryExtended(type, factory); } } else { for (String type : types) { _messageHandlerFactoriestobeAdded.put(type, factory); } } } public synchronized void onConnected() { for (String type : _messageHandlerFactoriestobeAdded.keySet()) { registerMessageHandlerFactoryExtended(type, _messageHandlerFactoriestobeAdded.get(type)); } _messageHandlerFactoriestobeAdded.clear(); } public HelixTaskExecutor getExecutor() { return _taskExecutor; } void registerMessageHandlerFactoryExtended(String type, MessageHandlerFactory factory) { int threadpoolSize = HelixTaskExecutor.DEFAULT_PARALLEL_TASKS; _taskExecutor.registerMessageHandlerFactory(type, factory, threadpoolSize); super.sendNopMessage(); } } }
9,682
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMsgUsingQueue.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.StringWriter; import java.util.Set; import java.util.UUID; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.apache.helix.Criteria; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.InstanceType; import org.apache.helix.PropertyKey; import org.apache.helix.integration.common.ZkStandAloneCMTestBase; import org.apache.helix.manager.zk.DefaultSchedulerMessageHandlerFactory; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageState; import org.apache.helix.model.Message.MessageType; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.testng.Assert; import org.testng.annotations.Test; public class TestSchedulerMsgUsingQueue extends ZkStandAloneCMTestBase { TestSchedulerMessage.TestMessagingHandlerFactory _factory = new TestSchedulerMessage.TestMessagingHandlerFactory(); @Test() public void testSchedulerMsgUsingQueue() throws Exception { // Logger.getRootLogger().setLevel(Level.INFO); _factory._results.clear(); Thread.sleep(2000); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory( _factory.getMessageType(), _factory); manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); schedulerMessage.getRecord().setSimpleField( DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE, "TestSchedulerMsg"); // Template for the individual message sent to each participant Message msg = new Message(_factory.getMessageType(), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("%"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = helixDataAccessor.keyBuilder(); helixDataAccessor.createControllerMessage(schedulerMessage); for (int i = 0; i < 30; i++) { Thread.sleep(2000); if (_PARTITIONS == _factory._results.size()) { break; } } Assert.assertEquals(_PARTITIONS, _factory._results.size()); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), schedulerMessage.getMsgId()); int messageResultCount = 0; for (int i = 0; i < 10; i++) { ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount") .equals("" + (_PARTITIONS * 3))); for (String key : statusUpdate.getMapFields().keySet()) { if (key.startsWith("MessageResult ")) { messageResultCount++; } } if (messageResultCount == _PARTITIONS * 3) { break; } else { Thread.sleep(2000); } } Assert.assertEquals(messageResultCount, _PARTITIONS * 3); int count = 0; for (Set<String> val : _factory._results.values()) { count += val.size(); } Assert.assertEquals(count, _PARTITIONS * 3); } }
9,683
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMsgContraints.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.StringWriter; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.apache.helix.Criteria; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.InstanceType; import org.apache.helix.PropertyKey; import org.apache.helix.integration.common.ZkStandAloneCMTestBase; import org.apache.helix.manager.zk.DefaultSchedulerMessageHandlerFactory; import org.apache.helix.model.ClusterConstraints.ConstraintType; import org.apache.helix.model.ConstraintItem; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageState; import org.apache.helix.model.Message.MessageType; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.testng.Assert; import org.testng.annotations.Test; public class TestSchedulerMsgContraints extends ZkStandAloneCMTestBase { @Test public void testSchedulerMsgContraints() throws Exception { TestSchedulerMessage.TestMessagingHandlerFactoryLatch factory = new TestSchedulerMessage.TestMessagingHandlerFactoryLatch(); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory( factory.getMessageType(), factory); _participants[i].getMessagingService().registerMessageHandlerFactory( factory.getMessageType(), factory); manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); // Template for the individual message sent to each participant Message msg = new Message(factory.getMessageType(), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("%"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); schedulerMessage.getRecord().setSimpleField("WAIT_ALL", "true"); schedulerMessage.getRecord().setSimpleField( DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE, "TestSchedulerMsgContraints"); Criteria cr2 = new Criteria(); cr2.setRecipientInstanceType(InstanceType.CONTROLLER); cr2.setInstanceName("*"); cr2.setSessionSpecific(false); TestSchedulerMessage.MockAsyncCallback callback = new TestSchedulerMessage.MockAsyncCallback(); mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); sw = new StringWriter(); mapper.writeValue(sw, cr); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = helixDataAccessor.keyBuilder(); // Set constraints that only 1 message per participant Map<String, String> constraints = new TreeMap<String, String>(); constraints.put("MESSAGE_TYPE", "STATE_TRANSITION"); constraints.put("TRANSITION", "OFFLINE-COMPLETED"); constraints.put("CONSTRAINT_VALUE", "1"); constraints.put("INSTANCE", ".*"); manager.getClusterManagmentTool().setConstraint(manager.getClusterName(), ConstraintType.MESSAGE_CONSTRAINT, "constraint1", new ConstraintItem(constraints)); // Send scheduler message crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1); String msgId = callback._message.getResultMap() .get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID); for (int j = 0; j < 10; j++) { Thread.sleep(200); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (statusUpdate.getMapFields().containsKey("SentMessageCount")) { Assert.assertEquals( statusUpdate.getMapFields().get("SentMessageCount").get("MessageCount"), "" + (_PARTITIONS * 3)); break; } } for (int i = 0; i < _PARTITIONS * 3 / 5; i++) { for (int j = 0; j < 10; j++) { Thread.sleep(300); if (factory._messageCount == 5 * (i + 1)) break; } Thread.sleep(300); Assert.assertEquals(factory._messageCount, 5 * (i + 1)); factory.signal(); // System.err.println(i); } for (int j = 0; j < 10; j++) { Thread.sleep(200); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (statusUpdate.getMapFields().containsKey("Summary")) { break; } } Assert.assertEquals(_PARTITIONS, factory._results.size()); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount") .equals("" + (_PARTITIONS * 3))); int messageResultCount = 0; for (String key : statusUpdate.getMapFields().keySet()) { if (key.startsWith("MessageResult ")) { messageResultCount++; } } Assert.assertEquals(messageResultCount, _PARTITIONS * 3); int count = 0; for (Set<String> val : factory._results.values()) { count += val.size(); } Assert.assertEquals(count, _PARTITIONS * 3); manager.getClusterManagmentTool().removeConstraint(manager.getClusterName(), ConstraintType.MESSAGE_CONSTRAINT, "constraint1"); } }
9,684
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestMessageThrottle.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.helix.HelixAdmin; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.TestHelper; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.common.ZkTestBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.manager.zk.ZKHelixAdmin; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.model.ClusterConstraints.ConstraintType; import org.apache.helix.model.Message; import org.apache.helix.model.builder.ConstraintItemBuilder; import org.apache.helix.tools.ClusterStateVerifier; import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier; import org.apache.helix.tools.ClusterStateVerifier.MasterNbInExtViewVerifier; import org.apache.helix.zookeeper.zkclient.IZkChildListener; import org.testng.Assert; import org.testng.annotations.Test; public class TestMessageThrottle extends ZkTestBase { @Test() public void testMessageThrottle() throws Exception { // Logger.getRootLogger().setLevel(Level.INFO); String clusterName = getShortClassName(); MockParticipantManager[] participants = new MockParticipantManager[5]; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant start // port "localhost", // participant name prefix "TestDB", // resource name prefix 1, // resources 10, // partitions per resource 5, // number of nodes 3, // replicas "MasterSlave", true); // do rebalance // setup message constraint // "MESSAGE_TYPE=STATE_TRANSITION,TRANSITION=OFFLINE-SLAVE,INSTANCE=.*,CONSTRAINT_VALUE=1"; HelixAdmin admin = new ZKHelixAdmin(_gZkClient); ConstraintItemBuilder builder = new ConstraintItemBuilder(); builder.addConstraintAttribute("MESSAGE_TYPE", "STATE_TRANSITION") .addConstraintAttribute("INSTANCE", ".*").addConstraintAttribute("CONSTRAINT_VALUE", "1"); // Map<String, String> constraints = new TreeMap<String, String>(); // constraints.put("MESSAGE_TYPE", "STATE_TRANSITION"); // // constraints.put("TRANSITION", "OFFLINE-SLAVE"); // constraints.put("CONSTRAINT_VALUE", "1"); // constraints.put("INSTANCE", ".*"); admin.setConstraint(clusterName, ConstraintType.MESSAGE_CONSTRAINT, "constraint1", builder.build()); final ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); // make sure we never see more than 1 state transition message for each participant final AtomicBoolean success = new AtomicBoolean(true); for (int i = 0; i < 5; i++) { String instanceName = "localhost_" + (12918 + i); String msgPath = PropertyPathBuilder.instanceMessage(clusterName, instanceName); _gZkClient.subscribeChildChanges(msgPath, new IZkChildListener() { @Override public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception { if (currentChilds != null && currentChilds.size() > 1) { List<ZNRecord> records = accessor.getBaseDataAccessor().getChildren(parentPath, null, 0, 0, 0); int transitionMsgCount = 0; for (ZNRecord record : records) { Message msg = new Message(record); if (msg.getMsgType().equals(Message.MessageType.STATE_TRANSITION.name())) { transitionMsgCount++; } } if (transitionMsgCount > 1) { success.set(false); Assert.fail("Should not see more than 1 message"); } } } }); } ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0"); controller.syncStart(); // start participants for (int i = 0; i < 5; i++) { String instanceName = "localhost_" + (12918 + i); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].syncStart(); } boolean result = ClusterStateVerifier .verifyByZkCallback(new MasterNbInExtViewVerifier(ZK_ADDR, clusterName)); Assert.assertTrue(result); result = ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName)); Assert.assertTrue(result); Assert.assertTrue(success.get()); // clean up controller.syncStop(); for (int i = 0; i < 5; i++) { participants[i].syncStop(); } TestHelper.dropCluster(clusterName, _gZkClient); System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } }
9,685
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestMessagingService.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashSet; import java.util.List; import java.util.UUID; import com.google.common.collect.ImmutableList; import org.apache.helix.Criteria; import org.apache.helix.Criteria.DataSource; import org.apache.helix.InstanceType; import org.apache.helix.NotificationContext; import org.apache.helix.integration.common.ZkStandAloneCMTestBase; import org.apache.helix.messaging.AsyncCallback; import org.apache.helix.messaging.handling.HelixTaskResult; import org.apache.helix.messaging.handling.MessageHandler; import org.apache.helix.messaging.handling.MultiTypeMessageHandlerFactory; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageState; import org.apache.helix.model.Message.MessageType; import org.testng.AssertJUnit; import org.testng.annotations.Test; public class TestMessagingService extends ZkStandAloneCMTestBase { public static class TestMessagingHandlerFactory implements MultiTypeMessageHandlerFactory { public static HashSet<String> _processedMsgIds = new HashSet<String>(); @Override public MessageHandler createHandler(Message message, NotificationContext context) { return new TestMessagingHandler(message, context); } @Override public List<String> getMessageTypes() { return ImmutableList.of("TestExtensibility"); } @Override public void reset() { // TODO Auto-generated method stub } public static class TestMessagingHandler extends MessageHandler { public TestMessagingHandler(Message message, NotificationContext context) { super(message, context); // TODO Auto-generated constructor stub } @Override public HelixTaskResult handleMessage() throws InterruptedException { HelixTaskResult result = new HelixTaskResult(); result.setSuccess(true); Thread.sleep(1000); System.out.println("TestMessagingHandler " + _message.getMsgId()); _processedMsgIds.add(_message.getRecord().getSimpleField("TestMessagingPara")); result.getTaskResultMap().put("ReplyMessage", "TestReplyMessage"); return result; } @Override public void onError(Exception e, ErrorCode code, ErrorType type) { // TODO Auto-generated method stub } } } @Test() public void TestMessageSimpleSend() throws Exception { String hostSrc = "localhost_" + START_PORT; String hostDest = "localhost_" + (START_PORT + 1); TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); String msgId = new UUID(123, 456).toString(); Message msg = new Message(factory.getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); // int nMsgs = _startCMResultMap.get(hostSrc)._manager.getMessagingService().send(cr, msg); int nMsgs = _participants[0].getMessagingService().send(cr, msg); AssertJUnit.assertTrue(nMsgs == 1); Thread.sleep(2500); // Thread.currentThread().join(); AssertJUnit.assertTrue(TestMessagingHandlerFactory._processedMsgIds.contains(para)); cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setDataSource(DataSource.IDEALSTATES); // nMsgs = _startCMResultMap.get(hostSrc)._manager.getMessagingService().send(cr, msg); nMsgs = _participants[0].getMessagingService().send(cr, msg); AssertJUnit.assertTrue(nMsgs == 1); Thread.sleep(2500); // Thread.currentThread().join(); AssertJUnit.assertTrue(TestMessagingHandlerFactory._processedMsgIds.contains(para)); } public static class MockAsyncCallback extends AsyncCallback { public MockAsyncCallback() { } @Override public void onTimeOut() { // TODO Auto-generated method stub } @Override public void onReplyMessage(Message message) { // TODO Auto-generated method stub } } public static class TestAsyncCallback extends AsyncCallback { public TestAsyncCallback(long timeout) { super(timeout); } static HashSet<String> _replyedMessageContents = new HashSet<String>(); public boolean timeout = false; @Override public void onTimeOut() { timeout = true; } @Override public void onReplyMessage(Message message) { // TODO Auto-generated method stub System.out.println("OnreplyMessage: " + message.getRecord().getMapField(Message.Attributes.MESSAGE_RESULT.toString()) .get("ReplyMessage")); if (message.getRecord().getMapField(Message.Attributes.MESSAGE_RESULT.toString()) .get("ReplyMessage") == null) { } _replyedMessageContents.add(message.getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage")); } } @Test() public void TestMessageSimpleSendReceiveAsync() throws Exception { String hostSrc = "localhost_" + START_PORT; String hostDest = "localhost_" + (START_PORT + 1); TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); _participants[0].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); String msgId = new UUID(123, 456).toString(); Message msg = new Message(factory.getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); TestAsyncCallback callback = new TestAsyncCallback(60000); _participants[0].getMessagingService().send(cr, msg, callback, 60000); Thread.sleep(2000); // Thread.currentThread().join(); AssertJUnit.assertTrue(TestAsyncCallback._replyedMessageContents.contains("TestReplyMessage")); AssertJUnit.assertTrue(callback.getMessageReplied().size() == 1); TestAsyncCallback callback2 = new TestAsyncCallback(500); _participants[0].getMessagingService().send(cr, msg, callback2, 500); Thread.sleep(3000); // Thread.currentThread().join(); AssertJUnit.assertTrue(callback2.isTimedOut()); cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setDataSource(DataSource.IDEALSTATES); callback = new TestAsyncCallback(60000); _participants[0].getMessagingService().send(cr, msg, callback, 60000); Thread.sleep(2000); // Thread.currentThread().join(); AssertJUnit.assertTrue(TestAsyncCallback._replyedMessageContents.contains("TestReplyMessage")); AssertJUnit.assertTrue(callback.getMessageReplied().size() == 1); callback2 = new TestAsyncCallback(500); _participants[0].getMessagingService().send(cr, msg, callback2, 500); Thread.sleep(3000); // Thread.currentThread().join(); AssertJUnit.assertTrue(callback2.isTimedOut()); } @Test() public void TestBlockingSendReceive() throws Exception { String hostSrc = "localhost_" + START_PORT; String hostDest = "localhost_" + (START_PORT + 1); TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(), factory); String msgId = new UUID(123, 456).toString(); Message msg = new Message(factory.getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName(hostDest); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); AsyncCallback asyncCallback = new MockAsyncCallback(); int messagesSent = _participants[0].getMessagingService().sendAndWait(cr, msg, asyncCallback, 60000); AssertJUnit.assertTrue(asyncCallback.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage") .equals("TestReplyMessage")); AssertJUnit.assertTrue(asyncCallback.getMessageReplied().size() == 1); AsyncCallback asyncCallback2 = new MockAsyncCallback(); messagesSent = _participants[0].getMessagingService().sendAndWait(cr, msg, asyncCallback2, 500); AssertJUnit.assertTrue(asyncCallback2.isTimedOut()); } @Test() public void TestMultiMessageCriteria() throws Exception { String hostSrc = "localhost_" + START_PORT; for (int i = 0; i < NODE_NR; i++) { TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); String hostDest = "localhost_" + (START_PORT + i); _participants[i].getMessagingService().registerMessageHandlerFactory( factory.getMessageTypes(), factory); } String msgId = new UUID(123, 456).toString(); Message msg = new Message(new TestMessagingHandlerFactory().getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName("%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); AsyncCallback callback1 = new MockAsyncCallback(); int messageSent1 = _participants[0].getMessagingService().sendAndWait(cr, msg, callback1, 10000); AssertJUnit.assertTrue(callback1.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage") .equals("TestReplyMessage")); AssertJUnit.assertTrue(callback1.getMessageReplied().size() == NODE_NR - 1); AsyncCallback callback2 = new MockAsyncCallback(); int messageSent2 = _participants[0].getMessagingService().sendAndWait(cr, msg, callback2, 500); AssertJUnit.assertTrue(callback2.isTimedOut()); cr.setPartition("TestDB_17"); AsyncCallback callback3 = new MockAsyncCallback(); int messageSent3 = _participants[0].getMessagingService().sendAndWait(cr, msg, callback3, 10000); AssertJUnit.assertTrue(callback3.getMessageReplied().size() == _replica - 1); cr.setPartition("TestDB_15"); AsyncCallback callback4 = new MockAsyncCallback(); int messageSent4 = _participants[0].getMessagingService().sendAndWait(cr, msg, callback4, 10000); AssertJUnit.assertTrue(callback4.getMessageReplied().size() == _replica); cr.setPartitionState("SLAVE"); AsyncCallback callback5 = new MockAsyncCallback(); int messageSent5 = _participants[0].getMessagingService().sendAndWait(cr, msg, callback5, 10000); AssertJUnit.assertTrue(callback5.getMessageReplied().size() == _replica - 1); cr.setDataSource(DataSource.IDEALSTATES); AsyncCallback callback6 = new MockAsyncCallback(); int messageSent6 = _participants[0].getMessagingService().sendAndWait(cr, msg, callback6, 10000); AssertJUnit.assertTrue(callback6.getMessageReplied().size() == _replica - 1); } @Test() public void sendSelfMsg() { String hostSrc = "localhost_" + START_PORT; for (int i = 0; i < NODE_NR; i++) { TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); String hostDest = "localhost_" + (START_PORT + i); _participants[i].getMessagingService().registerMessageHandlerFactory( factory.getMessageTypes(), factory); } String msgId = new UUID(123, 456).toString(); Message msg = new Message(new TestMessagingHandlerFactory().getMessageTypes().get(0), msgId); msg.setMsgId(msgId); msg.setSrcName(hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName("%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setSelfExcluded(false); AsyncCallback callback1 = new MockAsyncCallback(); int messageSent1 = _participants[0].getMessagingService().sendAndWait(cr, msg, callback1, 10000); AssertJUnit.assertTrue(callback1.getMessageReplied().size() == NODE_NR); AssertJUnit.assertTrue(callback1.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage") .equals("TestReplyMessage")); } @Test() public void TestControllerMessage() throws Exception { String hostSrc = "localhost_" + START_PORT; for (int i = 0; i < NODE_NR; i++) { TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory(); String hostDest = "localhost_" + (START_PORT + i); _participants[i].getMessagingService().registerMessageHandlerFactory( factory.getMessageTypes(), factory); } String msgId = new UUID(123, 456).toString(); Message msg = new Message(MessageType.CONTROLLER_MSG, msgId); msg.setMsgId(msgId); msg.setSrcName(hostSrc); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); String para = "Testing messaging para"; msg.getRecord().setSimpleField("TestMessagingPara", para); Criteria cr = new Criteria(); cr.setInstanceName("*"); cr.setRecipientInstanceType(InstanceType.CONTROLLER); cr.setSessionSpecific(false); AsyncCallback callback1 = new MockAsyncCallback(); int messagesSent = _participants[0].getMessagingService().sendAndWait(cr, msg, callback1, 10000); AssertJUnit.assertTrue(callback1.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult") .indexOf(hostSrc) != -1); AssertJUnit.assertTrue(callback1.getMessageReplied().size() == 1); msgId = UUID.randomUUID().toString(); msg.setMsgId(msgId); cr.setPartition("TestDB_17"); AsyncCallback callback2 = new MockAsyncCallback(); messagesSent = _participants[0].getMessagingService().sendAndWait(cr, msg, callback2, 10000); AssertJUnit.assertTrue(callback2.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult") .indexOf(hostSrc) != -1); AssertJUnit.assertTrue(callback2.getMessageReplied().size() == 1); msgId = UUID.randomUUID().toString(); msg.setMsgId(msgId); cr.setPartitionState("SLAVE"); AsyncCallback callback3 = new MockAsyncCallback(); messagesSent = _participants[0].getMessagingService().sendAndWait(cr, msg, callback3, 10000); AssertJUnit.assertTrue(callback3.getMessageReplied().get(0).getRecord() .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult") .indexOf(hostSrc) != -1); AssertJUnit.assertTrue(callback3.getMessageReplied().size() == 1); } }
9,686
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestMessageThrottle2.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.helix.ControllerChangeListener; import org.apache.helix.ExternalViewChangeListener; import org.apache.helix.HelixAdmin; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.IdealStateChangeListener; import org.apache.helix.InstanceConfigChangeListener; import org.apache.helix.InstanceType; import org.apache.helix.LiveInstanceChangeListener; import org.apache.helix.NotificationContext; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.TestHelper; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.common.ZkTestBase; import org.apache.helix.controller.HelixControllerMain; import org.apache.helix.manager.zk.ZKHelixAdmin; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZKHelixManager; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.model.ClusterConstraints; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.LiveInstance; import org.apache.helix.model.Message; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.model.builder.ConstraintItemBuilder; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.participant.statemachine.StateModel; import org.apache.helix.participant.statemachine.StateModelFactory; import org.apache.helix.participant.statemachine.StateModelInfo; import org.apache.helix.participant.statemachine.Transition; import org.apache.helix.tools.ClusterStateVerifier; import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; public class TestMessageThrottle2 extends ZkTestBase { private final static String _clusterName = "TestMessageThrottle2"; private final static String _resourceName = "MyResource"; private HelixManager _helixController; @Test public void test() throws Exception { System.out.println("START " + _clusterName + " at " + new Date(System.currentTimeMillis())); // Keep mock participant references so that they could be shut down after testing Set<MyProcess> participants = new HashSet<>(); startAdmin(); startController(); // start node2 first participants.add(Node.main(new String[] { "2" })); // wait for node2 becoming MASTER final Builder keyBuilder = new Builder(_clusterName); final HelixDataAccessor accessor = new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient)); TestHelper.verify(() -> { ExternalView view = accessor.getProperty(keyBuilder.externalView(_resourceName)); String state = null; if (view != null) { Map<String, String> map = view.getStateMap(_resourceName); if (map != null) { state = map.get("node2"); } } return state != null && state.equals("MASTER"); }, 10 * 1000); // start node 1 participants.add(Node.main(new String[] { "1" })); boolean result = ClusterStateVerifier .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName)); Assert.assertTrue(result); // Clean up after testing _helixController.disconnect(); participants.forEach(MyProcess::stop); deleteCluster(_clusterName); System.out.println("END " + _clusterName + " at " + new Date(System.currentTimeMillis())); } private void startController() throws Exception { // start _helixController System.out.println(String.format("Starting Controller{Cluster:%s, Port:%s, Zookeeper:%s}", _clusterName, 12000, ZK_ADDR)); _helixController = HelixControllerMain.startHelixController(ZK_ADDR, _clusterName, "localhost_" + 12000, HelixControllerMain.STANDALONE); // StatusPrinter statusPrinter = new StatusPrinter(); // statusPrinter.registerWith(_helixController); } 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()); } private ZNRecord generateConfigForMasterSlave() { ZNRecord record = new ZNRecord("MasterSlave"); record.setSimpleField( StateModelDefinition.StateModelDefinitionProperty.INITIAL_STATE.toString(), "OFFLINE"); List<String> statePriorityList = new ArrayList<>(); statePriorityList.add("MASTER"); statePriorityList.add("SLAVE"); statePriorityList.add("OFFLINE"); statePriorityList.add("DROPPED"); statePriorityList.add("ERROR"); record.setListField( StateModelDefinition.StateModelDefinitionProperty.STATE_PRIORITY_LIST.toString(), statePriorityList); for (String state : statePriorityList) { String key = state + ".meta"; Map<String, String> metadata = new HashMap<>(); switch (state) { case "MASTER": metadata.put("count", "1"); record.setMapField(key, metadata); break; case "SLAVE": metadata.put("count", "R"); record.setMapField(key, metadata); break; case "OFFLINE": case "DROPPED": case "ERROR": metadata.put("count", "-1"); record.setMapField(key, metadata); break; } } for (String state : statePriorityList) { String key = state + ".next"; switch (state) { case "MASTER": { Map<String, String> metadata = new HashMap<>(); metadata.put("SLAVE", "SLAVE"); metadata.put("OFFLINE", "SLAVE"); metadata.put("DROPPED", "SLAVE"); record.setMapField(key, metadata); break; } case "SLAVE": { Map<String, String> metadata = new HashMap<>(); metadata.put("MASTER", "MASTER"); metadata.put("OFFLINE", "OFFLINE"); metadata.put("DROPPED", "OFFLINE"); record.setMapField(key, metadata); break; } case "OFFLINE": { Map<String, String> metadata = new HashMap<>(); metadata.put("SLAVE", "SLAVE"); metadata.put("MASTER", "SLAVE"); metadata.put("DROPPED", "DROPPED"); record.setMapField(key, metadata); break; } case "ERROR": { Map<String, String> metadata = new HashMap<>(); metadata.put("OFFLINE", "OFFLINE"); record.setMapField(key, metadata); break; } } } // change the transition priority list List<String> stateTransitionPriorityList = new ArrayList<>(); stateTransitionPriorityList.add("SLAVE-MASTER"); stateTransitionPriorityList.add("OFFLINE-SLAVE"); stateTransitionPriorityList.add("MASTER-SLAVE"); stateTransitionPriorityList.add("SLAVE-OFFLINE"); stateTransitionPriorityList.add("OFFLINE-DROPPED"); record.setListField( StateModelDefinition.StateModelDefinitionProperty.STATE_TRANSITION_PRIORITYLIST.toString(), stateTransitionPriorityList); return record; } static final class MyProcess { private final String _instanceName; private HelixManager _helixManager; public MyProcess(String instanceName) { this._instanceName = instanceName; } public void start() throws Exception { _helixManager = new ZKHelixManager(_clusterName, _instanceName, InstanceType.PARTICIPANT, ZK_ADDR); { // hack to set sessionTimeout Field sessionTimeout = ZKHelixManager.class.getDeclaredField("_sessionTimeout"); sessionTimeout.setAccessible(true); sessionTimeout.setInt(_helixManager, 1000); } StateMachineEngine stateMach = _helixManager.getStateMachineEngine(); stateMach.registerStateModelFactory("MasterSlave", new MyStateModelFactory(_helixManager)); _helixManager.connect(); // StatusPrinter statusPrinter = new StatusPrinter(); // statusPrinter.registerWith(_helixManager); } public void stop() { _helixManager.disconnect(); } } @StateModelInfo(initialState = "OFFLINE", states = { "MASTER", "SLAVE", "ERROR" }) public static class MyStateModel extends StateModel { private static final Logger LOGGER = LoggerFactory.getLogger(MyStateModel.class); private final HelixManager helixManager; public MyStateModel(HelixManager helixManager) { this.helixManager = helixManager; } @Transition(to = "SLAVE", from = "OFFLINE") public void onBecomeSlaveFromOffline(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); String instanceName = message.getTgtName(); LOGGER.info(instanceName + " becomes SLAVE from OFFLINE for " + partitionName); } @Transition(to = "SLAVE", from = "MASTER") public void onBecomeSlaveFromMaster(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); String instanceName = message.getTgtName(); LOGGER.info(instanceName + " becomes SLAVE from MASTER for " + partitionName); } @Transition(to = "MASTER", from = "SLAVE") public void onBecomeMasterFromSlave(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); String instanceName = message.getTgtName(); LOGGER.info(instanceName + " becomes MASTER from SLAVE for " + partitionName); } @Transition(to = "OFFLINE", from = "SLAVE") public void onBecomeOfflineFromSlave(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); String instanceName = message.getTgtName(); LOGGER.info(instanceName + " becomes OFFLINE from SLAVE for " + partitionName); } @Transition(to = "DROPPED", from = "OFFLINE") public void onBecomeDroppedFromOffline(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); String instanceName = message.getTgtName(); LOGGER.info(instanceName + " becomes DROPPED from OFFLINE for " + partitionName); } @Transition(to = "OFFLINE", from = "ERROR") public void onBecomeOfflineFromError(Message message, NotificationContext context) { String partitionName = message.getPartitionName(); String instanceName = message.getTgtName(); LOGGER.info(instanceName + " becomes OFFLINE from ERROR for " + partitionName); } } static class MyStateModelFactory extends StateModelFactory<MyStateModel> { private final HelixManager helixManager; public MyStateModelFactory(HelixManager helixManager) { this.helixManager = helixManager; } @Override public MyStateModel createNewStateModel(String resource, String partitionName) { return new MyStateModel(helixManager); } } static class Node { // ------------------------------ FIELDS ------------------------------ private static final Logger LOGGER = LoggerFactory.getLogger(Node.class); // -------------------------- INNER CLASSES -------------------------- // --------------------------- main() method --------------------------- public static MyProcess main(String[] args) throws Exception { if (args.length < 1) { LOGGER.info("usage: id"); System.exit(0); } int id = Integer.parseInt(args[0]); String instanceName = "node" + id; addInstanceConfig(instanceName); // Return the thread so that it could be interrupted after testing return startProcess(instanceName); } private static void addInstanceConfig(String instanceName) { // add node to cluster if not already added ZKHelixAdmin admin = new ZKHelixAdmin(ZK_ADDR); InstanceConfig instanceConfig = null; try { instanceConfig = admin.getInstanceConfig(_clusterName, instanceName); } catch (Exception ignored) { } if (instanceConfig == null) { InstanceConfig config = new InstanceConfig(instanceName); config.setHostName("localhost"); config.setInstanceEnabled(true); echo("Adding InstanceConfig:" + config); admin.addInstance(_clusterName, config); } } public static void echo(Object obj) { LOGGER.info(obj.toString()); } private static MyProcess startProcess(String instanceName) throws Exception { MyProcess process = new MyProcess(instanceName); process.start(); return process; } } static class StatusPrinter implements IdealStateChangeListener, InstanceConfigChangeListener, ExternalViewChangeListener, LiveInstanceChangeListener, ControllerChangeListener { // ------------------------------ FIELDS ------------------------------ // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface ControllerChangeListener // --------------------- @Override public void onControllerChange(NotificationContext changeContext) { System.out.println("StatusPrinter.onControllerChange:" + changeContext); } // --------------------- Interface ExternalViewChangeListener // --------------------- @Override public void onExternalViewChange(List<ExternalView> externalViewList, NotificationContext changeContext) { for (ExternalView externalView : externalViewList) { System.out .println("StatusPrinter.onExternalViewChange:" + "externalView = " + externalView); } } // --------------------- Interface IdealStateChangeListener // --------------------- @Override public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) { for (IdealState state : idealState) { System.out.println("StatusPrinter.onIdealStateChange:" + "state = " + state); } } // --------------------- Interface InstanceConfigChangeListener // --------------------- @Override public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs, NotificationContext context) { for (InstanceConfig instanceConfig : instanceConfigs) { System.out.println( "StatusPrinter.onInstanceConfigChange:" + "instanceConfig = " + instanceConfig); } } // --------------------- Interface LiveInstanceChangeListener // --------------------- @Override public void onLiveInstanceChange(List<LiveInstance> liveInstances, NotificationContext changeContext) { for (LiveInstance liveInstance : liveInstances) { System.out .println("StatusPrinter.onLiveInstanceChange:" + "liveInstance = " + liveInstance); } } // -------------------------- OTHER METHODS -------------------------- void registerWith(HelixManager helixManager) throws Exception { helixManager.addIdealStateChangeListener(this); helixManager.addInstanceConfigChangeListener(this); helixManager.addExternalViewChangeListener(this); helixManager.addLiveInstanceChangeListener(this); helixManager.addControllerListener(this); } } }
9,687
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PMessageSemiAuto.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixDataAccessor; import org.apache.helix.TestHelper; import org.apache.helix.common.ZkTestBase; import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider; import org.apache.helix.integration.DelayedTransitionBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.model.BuiltInStateModelDefinitions; import org.apache.helix.model.CurrentState; import org.apache.helix.model.LiveInstance; import org.apache.helix.model.MasterSlaveSMD; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestP2PMessageSemiAuto extends ZkTestBase { final String CLASS_NAME = getShortClassName(); final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME; static final int PARTICIPANT_NUMBER = 3; static final int PARTICIPANT_START_PORT = 12918; static final String DB_NAME_1 = "TestDB_1"; static final String DB_NAME_2 = "TestDB_2"; static final int PARTITION_NUMBER = 200; static final int REPLICA_NUMBER = 3; List<MockParticipantManager> _participants = new ArrayList<>(); List<String> _instances = new ArrayList<>(); ClusterControllerManager _controller; ZkHelixClusterVerifier _clusterVerifier; ConfigAccessor _configAccessor; HelixDataAccessor _accessor; @BeforeClass public void beforeClass() throws Exception { super.beforeClass(); System.out .println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis())); // setup storage cluster _gSetupTool.addCluster(CLUSTER_NAME, true); for (int i = 0; i < PARTICIPANT_NUMBER; i++) { String instance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance); _instances.add(instance); } // start dummy participants for (int i = 0; i < PARTICIPANT_NUMBER; i++) { MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _instances.get(i)); participant.setTransition(new DelayedTransitionBase(50)); participant.syncStart(); _participants.add(participant); } createDBInSemiAuto(_gSetupTool, CLUSTER_NAME, DB_NAME_1, _instances, BuiltInStateModelDefinitions.MasterSlave.name(), PARTITION_NUMBER, REPLICA_NUMBER); createDBInSemiAuto(_gSetupTool, CLUSTER_NAME, DB_NAME_2, _instances, BuiltInStateModelDefinitions.MasterSlave.name(), PARTITION_NUMBER, REPLICA_NUMBER); // start controller String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); _configAccessor = new ConfigAccessor(_gZkClient); _accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor); } @AfterClass public void afterClass() throws Exception { _controller.syncStop(); for (MockParticipantManager p : _participants) { p.syncStop(); } deleteCluster(CLUSTER_NAME); System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); } @Test public void testP2PStateTransitionDisabled() { // disable the master instance String prevMasterInstance = _instances.get(0); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, false); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1); verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1); // re-enable the old master _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, true); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PMessage(DB_NAME_1, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1); verifyP2PMessage(DB_NAME_2, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1); } @Test(dependsOnMethods = { "testP2PStateTransitionDisabled" }) public void testP2PStateTransitionEnabledInCluster() { enableP2PInCluster(CLUSTER_NAME, _configAccessor, true); enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_1, false); enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_2, false); // disable the master instance String prevMasterInstance = _instances.get(0); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, false); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), prevMasterInstance); verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), prevMasterInstance); // re-enable the old master _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, true); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PMessage(DB_NAME_1, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _instances.get(1)); verifyP2PMessage(DB_NAME_2, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _instances.get(1)); } @Test(dependsOnMethods = { "testP2PStateTransitionDisabled" }) public void testP2PStateTransitionEnabledInResource() { enableP2PInCluster(CLUSTER_NAME, _configAccessor, false); enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_1, true); enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_2, false); // disable the master instance String prevMasterInstance = _instances.get(0); _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, false); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), prevMasterInstance); verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1); // re-enable the old master _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, true); Assert.assertTrue(_clusterVerifier.verifyByPolling()); verifyP2PMessage(DB_NAME_1, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _instances.get(1)); verifyP2PMessage(DB_NAME_2, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1); } private void verifyP2PMessage(String dbName, String instance, String expectedState, String expectedTriggerHost) { // Use 0.1 as the expected ratio. Here we want to check the presence of P2P messages verifyP2PMessage(dbName, instance, expectedState, expectedTriggerHost, 0.1); } private void verifyP2PMessage(String dbName, String instance, String expectedState, String expectedTriggerHost, double expectedRatio) { ResourceControllerDataProvider dataCache = new ResourceControllerDataProvider(CLUSTER_NAME); dataCache.refresh(_accessor); Map<String, LiveInstance> liveInstanceMap = dataCache.getLiveInstances(); LiveInstance liveInstance = liveInstanceMap.get(instance); Map<String, CurrentState> currentStateMap = dataCache.getCurrentState(instance, liveInstance.getEphemeralOwner()); Assert.assertNotNull(currentStateMap); CurrentState currentState = currentStateMap.get(dbName); Assert.assertNotNull(currentState); Assert.assertEquals(currentState.getPartitionStateMap().size(), PARTITION_NUMBER); int total = 0; int expectedHost = 0; for (String partition : currentState.getPartitionStateMap().keySet()) { String state = currentState.getState(partition); Assert.assertEquals(state, expectedState, dbName + " Partition " + partition + "'s state is different as expected!"); String triggerHost = currentState.getTriggerHost(partition); if (triggerHost.equals(expectedTriggerHost)) { expectedHost++; } total++; } double ratio = ((double) expectedHost) / ((double) total); Assert.assertTrue(ratio >= expectedRatio, String.format( "Only %d out of %d percent transitions to Master were triggered by expected host!", expectedHost, total)); } }
9,688
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/messaging/TestBatchMessageWrapper.java
package org.apache.helix.integration.messaging; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Date; import org.apache.helix.NotificationContext; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.TestHelper; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.ZkUnitTestBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.messaging.handling.BatchMessageWrapper; import org.apache.helix.mock.participant.MockMSModelFactory; import org.apache.helix.model.IdealState; import org.apache.helix.model.Message; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.testng.Assert; import org.testng.annotations.Test; public class TestBatchMessageWrapper extends ZkUnitTestBase { class MockBatchMsgWrapper extends BatchMessageWrapper { int _startCount = 0; int _endCount = 0; @Override public void start(Message batchMsg, NotificationContext context) { // System.out.println("test batchMsg.start() invoked, " + batchMsg.getTgtName()); _startCount++; } @Override public void end(Message batchMsg, NotificationContext context) { // System.out.println("test batchMsg.end() invoked, " + batchMsg.getTgtName()); _endCount++; } } class TestMockMSModelFactory extends MockMSModelFactory { @Override public BatchMessageWrapper createBatchMessageWrapper(String resourceName) { return new MockBatchMsgWrapper(); } } @Test public void testBasic() throws Exception { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; final int n = 2; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // startPort "localhost", // participantNamePrefix "TestDB", // resourceNamePrefix 1, // resourceNb 2, // partitionNb n, // nodesNb 2, // replica "MasterSlave", true); // enable batch-message ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); Builder keyBuilder = accessor.keyBuilder(); IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0")); idealState.setBatchMessageMode(true); accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState); ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0"); controller.syncStart(); // start participants MockParticipantManager[] participants = new MockParticipantManager[n]; TestMockMSModelFactory[] ftys = new TestMockMSModelFactory[n]; for (int i = 0; i < n; i++) { String instanceName = "localhost_" + (12918 + i); ftys[i] = new TestMockMSModelFactory(); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].getStateMachineEngine().registerStateModelFactory("MasterSlave", ftys[i]); participants[i].syncStart(); int finalI = i; TestHelper.verify(() -> participants[finalI].isConnected() && accessor.getChildNames(keyBuilder.liveInstances()) .contains(participants[finalI].getInstanceName()), TestHelper.WAIT_DURATION); // wait for each participant to complete state transitions, so we have deterministic results ZkHelixClusterVerifier _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling(), "participant: " + instanceName + " fails to complete all transitions"); } // check batch-msg-wrapper counts MockBatchMsgWrapper wrapper = (MockBatchMsgWrapper) ftys[0].getBatchMessageWrapper("TestDB0"); // System.out.println("startCount: " + wrapper._startCount); Assert.assertEquals(wrapper._startCount, 3, "Expect 3 batch.start: O->S, S->M, and M->S for 1st participant"); // System.out.println("endCount: " + wrapper._endCount); Assert.assertEquals(wrapper._endCount, 3, "Expect 3 batch.end: O->S, S->M, and M->S for 1st participant"); wrapper = (MockBatchMsgWrapper) ftys[1].getBatchMessageWrapper("TestDB0"); // System.out.println("startCount: " + wrapper._startCount); Assert.assertEquals(wrapper._startCount, 2, "Expect 2 batch.start: O->S and S->M for 2nd participant"); // System.out.println("endCount: " + wrapper._endCount); Assert.assertEquals(wrapper._startCount, 2, "Expect 2 batch.end: O->S and S->M for 2nd participant"); // clean up controller.syncStop(); for (int i = 0; i < n; i++) { participants[i].syncStop(); } TestHelper.dropCluster(clusterName, _gZkClient); System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } }
9,689
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/MockHelixAdmin.java
package org.apache.helix.mock; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.List; import java.util.Map; import org.apache.helix.AccessOption; import org.apache.helix.BaseDataAccessor; import org.apache.helix.HelixAdmin; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.HelixManager; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.PropertyType; import org.apache.helix.api.status.ClusterManagementMode; import org.apache.helix.api.status.ClusterManagementModeRequest; import org.apache.helix.api.topology.ClusterTopology; import org.apache.helix.constants.InstanceConstants; import org.apache.helix.model.CloudConfig; import org.apache.helix.model.ClusterConfig; import org.apache.helix.model.ClusterConstraints; import org.apache.helix.model.ConstraintItem; import org.apache.helix.model.CustomizedStateConfig; import org.apache.helix.model.CustomizedView; import org.apache.helix.model.ExternalView; import org.apache.helix.model.HelixConfigScope; import org.apache.helix.model.IdealState; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.MaintenanceSignal; import org.apache.helix.model.ResourceConfig; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.zkclient.DataUpdater; public class MockHelixAdmin implements HelixAdmin { private HelixDataAccessor _dataAccessor; private BaseDataAccessor _baseDataAccessor; public MockHelixAdmin(HelixManager manager) { _dataAccessor = manager.getHelixDataAccessor(); _baseDataAccessor = _dataAccessor.getBaseDataAccessor(); } @Override public List<String> getClusters() { return null; } @Override public List<String> getInstancesInCluster(String clusterName) { return null; } @Override public InstanceConfig getInstanceConfig(String clusterName, String instanceName) { return null; } @Override public boolean setInstanceConfig(String clusterName, String instanceName, InstanceConfig instanceConfig) { return false; } @Override public List<String> getResourcesInCluster(String clusterName) { return null; } @Override public List<String> getResourcesInClusterWithTag(String clusterName, String tag) { return null; } @Override public boolean addCluster(String clusterName) { return addCluster(clusterName, false); } @Override public boolean addCluster(String clusterName, boolean recreateIfExists) { String root = "/" + clusterName; _baseDataAccessor.exists(root, 0); createZKPaths(clusterName); return true; } private void createZKPaths(String clusterName) { String path; // IDEAL STATE _baseDataAccessor .create(PropertyPathBuilder.idealState(clusterName), new ZNRecord(clusterName), 0); // CONFIGURATIONS path = PropertyPathBuilder.clusterConfig(clusterName); _baseDataAccessor.create(path, new ClusterConfig(clusterName).getRecord(), 0); path = PropertyPathBuilder.instanceConfig(clusterName); _baseDataAccessor.create(path, new ZNRecord(clusterName), 0); path = PropertyPathBuilder.resourceConfig(clusterName); _baseDataAccessor.create(path, new ZNRecord(clusterName), 0); path = PropertyPathBuilder.customizedStateConfig(clusterName); _baseDataAccessor.create(path, new ZNRecord(clusterName), 0); // PROPERTY STORE path = PropertyPathBuilder.propertyStore(clusterName); _baseDataAccessor.create(path, new ZNRecord(clusterName), 0); // LIVE INSTANCES _baseDataAccessor .create(PropertyPathBuilder.liveInstance(clusterName), new ZNRecord(clusterName), 0); // MEMBER INSTANCES _baseDataAccessor .create(PropertyPathBuilder.instance(clusterName), new ZNRecord(clusterName), 0); // External view _baseDataAccessor .create(PropertyPathBuilder.externalView(clusterName), new ZNRecord(clusterName), 0); // State model definition _baseDataAccessor .create(PropertyPathBuilder.stateModelDef(clusterName), new ZNRecord(clusterName), 0); // controller _baseDataAccessor .create(PropertyPathBuilder.controller(clusterName), new ZNRecord(clusterName), 0); path = PropertyPathBuilder.controllerHistory(clusterName); final ZNRecord emptyHistory = new ZNRecord(PropertyType.HISTORY.toString()); final List<String> emptyList = new ArrayList<String>(); emptyHistory.setListField(clusterName, emptyList); _baseDataAccessor.create(path, emptyHistory, 0); path = PropertyPathBuilder.controllerMessage(clusterName); _baseDataAccessor.create(path, new ZNRecord(clusterName), 0); path = PropertyPathBuilder.controllerStatusUpdate(clusterName); _baseDataAccessor.create(path, new ZNRecord(clusterName), 0); path = PropertyPathBuilder.controllerError(clusterName); _baseDataAccessor.create(path, new ZNRecord(clusterName), 0); } @Override public void addClusterToGrandCluster(String clusterName, String grandCluster) { } @Override public void addCustomizedStateConfig(String clusterName, CustomizedStateConfig customizedStateConfig) { } @Override public void removeCustomizedStateConfig(String clusterName) { } @Override public void addTypeToCustomizedStateConfig(String clusterName, String type) { } @Override public void removeTypeFromCustomizedStateConfig(String clusterName, String type) { } @Override public void addResource(String clusterName, String resourceName, int numPartitions, String stateModelRef) { } @Override public void addResource(String clusterName, String resourceName, IdealState idealstate) { } @Override public void addResource(String clusterName, String resourceName, int numPartitions, String stateModelRef, String rebalancerMode) { } @Override public void addResource(String clusterName, String resourceName, int numPartitions, String stateModelRef, String rebalancerMode, String rebalanceStrategy) { } @Override public void addResource(String clusterName, String resourceName, int numPartitions, String stateModelRef, String rebalancerMode, int bucketSize) { } @Override public void addResource(String clusterName, String resourceName, int numPartitions, String stateModelRef, String rebalancerMode, int bucketSize, int maxPartitionsPerInstance) { } @Override public void addResource(String clusterName, String resourceName, int numPartitions, String stateModelRef, String rebalancerMode, String rebalanceStrategy, int bucketSize, int maxPartitionsPerInstance) { } @Override public void addInstance(String clusterName, InstanceConfig instanceConfig) { String instanceConfigsPath = PropertyPathBuilder.instanceConfig(clusterName); String nodeId = instanceConfig.getId(); if (!_baseDataAccessor.exists(instanceConfigsPath, 0)) { _baseDataAccessor.create(instanceConfigsPath, new ZNRecord(nodeId), 0); } String instanceConfigPath = instanceConfigsPath + "/" + nodeId; _baseDataAccessor.create(instanceConfigPath, instanceConfig.getRecord(), 0); _baseDataAccessor .set(PropertyPathBuilder.instanceMessage(clusterName, nodeId), new ZNRecord(nodeId), 0); _baseDataAccessor .set(PropertyPathBuilder.instanceCurrentState(clusterName, nodeId), new ZNRecord(nodeId), 0); _baseDataAccessor.set(PropertyPathBuilder.instanceTaskCurrentState(clusterName, nodeId), new ZNRecord(nodeId), 0); _baseDataAccessor .set(PropertyPathBuilder.instanceCustomizedState(clusterName, nodeId), new ZNRecord(nodeId), 0); _baseDataAccessor .set(PropertyPathBuilder.instanceError(clusterName, nodeId), new ZNRecord(nodeId), 0); _baseDataAccessor .set(PropertyPathBuilder.instanceStatusUpdate(clusterName, nodeId), new ZNRecord(nodeId), 0); _baseDataAccessor .set(PropertyPathBuilder.instanceHistory(clusterName, nodeId), new ZNRecord(nodeId), 0); } @Override public void dropInstance(String clusterName, InstanceConfig instanceConfig) { } @Override public void purgeOfflineInstances(String clusterName, long offlineDuration) { } @Override public IdealState getResourceIdealState(String clusterName, String resourceName) { return null; } @Override public void setResourceIdealState(String clusterName, String resourceName, IdealState idealState) { } @Override public void updateIdealState(String clusterName, String resourceName, IdealState idealState) { } @Override public void removeFromIdealState(String clusterName, String resourceName, IdealState idealState) { } @Override public void enableInstance(String clusterName, String instanceName, boolean enabled) { enableInstance(clusterName, instanceName, enabled, null, null); } @Override public void enableInstance(String clusterName, String instanceName, boolean enabled, InstanceConstants.InstanceDisabledType disabledType, String reason) { String instanceConfigsPath = PropertyPathBuilder.instanceConfig(clusterName); if (!_baseDataAccessor.exists(instanceConfigsPath, 0)) { _baseDataAccessor.create(instanceConfigsPath, new ZNRecord(instanceName), 0); } String instanceConfigPath = instanceConfigsPath + "/" + instanceName; ZNRecord record = (ZNRecord) _baseDataAccessor.get(instanceConfigPath, null, 0); InstanceConfig instanceConfig = new InstanceConfig(record); instanceConfig.setInstanceEnabled(enabled); if (!enabled) { instanceConfig.resetInstanceDisabledTypeAndReason(); if (reason != null) { instanceConfig.setInstanceDisabledReason(reason); } if (disabledType != null) { instanceConfig.setInstanceDisabledType(disabledType); } } _baseDataAccessor.set(instanceConfigPath, instanceConfig.getRecord(), 0); } @Override public void enableInstance(String clusterName, List<String> instances, boolean enabled) { } @Override public void setInstanceOperation(String clusterName, String instanceName, InstanceConstants.InstanceOperation instanceOperation) { } @Override public void enableResource(String clusterName, String resourceName, boolean enabled) { } @Override public void enablePartition(boolean enabled, String clusterName, String instanceName, String resourceName, List<String> partitionNames) { } @Override public void enableCluster(String clusterName, boolean enabled) { } @Override public void enableCluster(String clusterName, boolean enabled, String reason) { } @Override public void enableMaintenanceMode(String clusterName, boolean enabled) { } @Override public void enableMaintenanceMode(String clusterName, boolean enabled, String reason) { } @Override public void autoEnableMaintenanceMode(String clusterName, boolean enabled, String reason, MaintenanceSignal.AutoTriggerReason internalReason) { } @Override public void manuallyEnableMaintenanceMode(String clusterName, boolean enabled, String reason, Map<String, String> customFields) { } @Override public boolean isInMaintenanceMode(String clusterName) { return false; } @Override public void setClusterManagementMode(ClusterManagementModeRequest request) { } @Override public ClusterManagementMode getClusterManagementMode(String clusterName) { return null; } @Override public void resetPartition(String clusterName, String instanceName, String resourceName, List<String> partitionNames) { } @Override public void resetInstance(String clusterName, List<String> instanceNames) { } @Override public void resetResource(String clusterName, List<String> resourceNames) { } @Override public void addStateModelDef(String clusterName, String stateModelDef, StateModelDefinition record) { } @Override public void addStateModelDef(String clusterName, String stateModelDef, StateModelDefinition record, boolean recreateIfExists) { } @Override public void dropResource(String clusterName, String resourceName) { } @Override public void addCloudConfig(String clusterName, CloudConfig cloudConfig) { } @Override public void removeCloudConfig(String clusterName) { } @Override public ClusterTopology getClusterTopology(String clusterName) { return null; } @Override public List<String> getStateModelDefs(String clusterName) { return null; } @Override public StateModelDefinition getStateModelDef(String clusterName, String stateModelName) { return null; } @Override public ExternalView getResourceExternalView(String clusterName, String resourceName) { return null; } @Override public CustomizedView getResourceCustomizedView(String clusterName, String resourceName, String customizedStateType) { return null; } @Override public void dropCluster(String clusterName) { } @Override public void setConfig(HelixConfigScope scope, Map<String, String> properties) { } @Override public void removeConfig(HelixConfigScope scope, List<String> keys) { } @Override public Map<String, String> getConfig(HelixConfigScope scope, List<String> keys) { return null; } @Override public List<String> getConfigKeys(HelixConfigScope scope) { return null; } @Override public void rebalance(String clusterName, String resourceName, int replica) { } @Override public void onDemandRebalance(String clusterName) {} @Override public void addIdealState(String clusterName, String resourceName, String idealStateFile) throws IOException { } @Override public void addStateModelDef(String clusterName, String stateModelDefName, String stateModelDefFile) throws IOException { } @Override public void setConstraint(String clusterName, ClusterConstraints.ConstraintType constraintType, String constraintId, ConstraintItem constraintItem) { } @Override public void removeConstraint(String clusterName, ClusterConstraints.ConstraintType constraintType, String constraintId) { } @Override public ClusterConstraints getConstraints(String clusterName, ClusterConstraints.ConstraintType constraintType) { return null; } @Override public void rebalance(String clusterName, IdealState currentIdealState, List<String> instanceNames) { } @Override public void rebalance(String clusterName, String resourceName, int replica, List<String> instances) { } @Override public void rebalance(String clusterName, String resourceName, int replica, String keyPrefix, String group) { } @Override public List<String> getInstancesInClusterWithTag(String clusterName, String tag) { return null; } @Override public void addInstanceTag(String clusterName, String instanceName, String tag) { } @Override public void removeInstanceTag(String clusterName, String instanceName, String tag) { } @Override public void setInstanceZoneId(String clusterName, String instanceName, String zoneId) { } @Override public void enableBatchMessageMode(String clusterName, boolean enabled) { } @Override public void enableBatchMessageMode(String clusterName, String resourceName, boolean enabled) { } @Override public Map<String, String> getBatchDisabledInstances(String clusterName) { return null; } @Override public List<String> getInstancesByDomain(String clusterName, String domain) { return null; } @Override public void close() { } @Override public boolean addResourceWithWeight(String clusterName, IdealState idealState, ResourceConfig resourceConfig) { return false; } @Override public boolean enableWagedRebalance(String clusterName, List<String> resourceNames) { return false; } @Override public Map<String, Boolean> validateResourcesForWagedRebalance(String clusterName, List<String> resourceNames) { return null; } @Override public Map<String, Boolean> validateInstancesForWagedRebalance(String clusterName, List<String> instancesNames) { return null; } @Override public boolean isEvacuateFinished(String clusterName, String instancesNames) { return false; } @Override public boolean isReadyForPreparingJoiningCluster(String clusterName, String instancesNames) { return false; } }
9,690
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/MockZkClient.java
package org.apache.helix.mock; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.helix.manager.zk.ZNRecordSerializer; import org.apache.helix.manager.zk.ZkAsyncCallbacks; import org.apache.helix.zookeeper.impl.client.ZkClient; import org.apache.helix.zookeeper.api.client.HelixZkClient; public class MockZkClient extends ZkClient implements HelixZkClient { Map<String, byte[]> _dataMap; public MockZkClient(String zkAddress) { super(zkAddress); _dataMap = new HashMap<>(); setZkSerializer(new ZNRecordSerializer()); } @Override public void asyncGetData(final String path, final ZkAsyncCallbacks.GetDataCallbackHandler cb) { if (_dataMap.containsKey(path)) { if (_dataMap.get(path) == null) { cb.processResult(4, path, null, _dataMap.get(path), null); } else { cb.processResult(0, path, null, _dataMap.get(path), null); } } else { super.asyncGetData(path, cb); } } public List<String> getChildren(final String path) { List<String> children = super.getChildren(path); for (String p : _dataMap.keySet()) { if (p.contains(path)) { String[] paths = p.split("/"); children.add(paths[paths.length-1]); } } return children; } public void putData(String path, byte[] data) { _dataMap.put(path, data); } public byte[] removeData(String path) { return _dataMap.remove(path); } }
9,691
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/MockManager.java
package org.apache.helix.mock; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Set; import java.util.UUID; import org.apache.helix.ClusterMessagingService; import org.apache.helix.ConfigAccessor; import org.apache.helix.HelixAdmin; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerProperties; import org.apache.helix.InstanceType; import org.apache.helix.LiveInstanceInfoProvider; import org.apache.helix.MockAccessor; import org.apache.helix.PreConnectCallback; import org.apache.helix.PropertyKey; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.api.listeners.ClusterConfigChangeListener; import org.apache.helix.api.listeners.ConfigChangeListener; import org.apache.helix.api.listeners.ControllerChangeListener; import org.apache.helix.api.listeners.CurrentStateChangeListener; import org.apache.helix.api.listeners.CustomizedStateChangeListener; import org.apache.helix.api.listeners.CustomizedStateConfigChangeListener; import org.apache.helix.api.listeners.CustomizedStateRootChangeListener; import org.apache.helix.api.listeners.CustomizedViewChangeListener; import org.apache.helix.api.listeners.CustomizedViewRootChangeListener; import org.apache.helix.api.listeners.ExternalViewChangeListener; import org.apache.helix.api.listeners.IdealStateChangeListener; import org.apache.helix.api.listeners.InstanceConfigChangeListener; import org.apache.helix.api.listeners.LiveInstanceChangeListener; import org.apache.helix.api.listeners.MessageListener; import org.apache.helix.api.listeners.ResourceConfigChangeListener; import org.apache.helix.api.listeners.ScopedConfigChangeListener; import org.apache.helix.controller.pipeline.Pipeline; import org.apache.helix.healthcheck.ParticipantHealthReportCollector; import org.apache.helix.model.HelixConfigScope; import org.apache.helix.participant.HelixStateMachineEngine; import org.apache.helix.participant.StateMachineEngine; import org.apache.helix.store.zk.ZkHelixPropertyStore; public class MockManager implements HelixManager { MockAccessor accessor; private final String _clusterName; private final String _sessionId; String _instanceName; ClusterMessagingService _msgSvc; private String _version; HelixManagerProperties _properties = new HelixManagerProperties(); public MockManager() { this("testCluster-" + Math.random() * 10000 % 999); } public MockManager(String clusterName) { _clusterName = clusterName; accessor = new MockAccessor(clusterName); _sessionId = UUID.randomUUID().toString(); _instanceName = "testInstanceName"; _msgSvc = new MockClusterMessagingService(); } @Override public void disconnect() { } @Override public void addIdealStateChangeListener(IdealStateChangeListener listener) throws Exception { // TODO Auto-generated method stub } @Override public void addIdealStateChangeListener(org.apache.helix.IdealStateChangeListener listener) throws Exception { } @Override public void addLiveInstanceChangeListener(LiveInstanceChangeListener listener) { // TODO Auto-generated method stub } @Override public void addLiveInstanceChangeListener(org.apache.helix.LiveInstanceChangeListener listener) throws Exception { } @Override public void addConfigChangeListener(ConfigChangeListener listener) { // TODO Auto-generated method stub } @Override public void addMessageListener(MessageListener listener, String instanceName) { // TODO Auto-generated method stub } @Override public void addMessageListener(org.apache.helix.MessageListener listener, String instanceName) throws Exception { } @Override public void addCurrentStateChangeListener(CurrentStateChangeListener listener, String instanceName, String sessionId) { // TODO Auto-generated method stub } @Override public void addCurrentStateChangeListener(org.apache.helix.CurrentStateChangeListener listener, String instanceName, String sessionId) throws Exception { } @Override public void addCustomizedStateRootChangeListener(CustomizedStateRootChangeListener listener, String instanceName) { // TODO Auto-generated method stub } @Override public void addCustomizedStateChangeListener(CustomizedStateChangeListener listener, String instanceName, String customizedStateType) { // TODO Auto-generated method stub } @Override public void addExternalViewChangeListener(ExternalViewChangeListener listener) { // TODO Auto-generated method stub } @Override public void addCustomizedViewChangeListener(CustomizedViewChangeListener listener, String customizedStateType) { // TODO Auto-generated method stub } public void addCustomizedViewRootChangeListener(CustomizedViewRootChangeListener listener) throws Exception { // TODO Auto-generated method stub } @Override public void addTargetExternalViewChangeListener(ExternalViewChangeListener listener) throws Exception { // TODO Auto-generated method stub } @Override public void addExternalViewChangeListener(org.apache.helix.ExternalViewChangeListener listener) throws Exception { } @Override public void addResourceConfigChangeListener(ResourceConfigChangeListener listener) throws Exception { } @Override public void addCustomizedStateConfigChangeListener(CustomizedStateConfigChangeListener listener) throws Exception { } @Override public void addClusterfigChangeListener(ClusterConfigChangeListener listener) throws Exception { } @Override public void setEnabledControlPipelineTypes(Set<Pipeline.Type> types) { } @Override public String getClusterName() { return _clusterName; } @Override public String getMetadataStoreConnectionString() { return null; } @Override public String getInstanceName() { return _instanceName; } @Override public void connect() { // TODO Auto-generated method stub } @Override public String getSessionId() { return _sessionId; } @Override public boolean isConnected() { // TODO Auto-generated method stub return false; } @Override public long getLastNotificationTime() { // TODO Auto-generated method stub return 0; } @Override public void addControllerListener(ControllerChangeListener listener) { // TODO Auto-generated method stub } @Override public void addControllerListener(org.apache.helix.ControllerChangeListener listener) { } @Override public boolean removeListener(PropertyKey key, Object listener) { // TODO Auto-generated method stub return false; } @Override public HelixAdmin getClusterManagmentTool() { return new MockHelixAdmin(this); } @Override public ClusterMessagingService getMessagingService() { // TODO Auto-generated method stub return _msgSvc; } @Override public InstanceType getInstanceType() { return InstanceType.PARTICIPANT; } @Override public String getVersion() { return _version; } public void setVersion(String version) { _properties.getProperties().put("clustermanager.version", version); _version = version; } @Override public StateMachineEngine getStateMachineEngine() { return new HelixStateMachineEngine(this); } @Override public boolean isLeader() { // TODO Auto-generated method stub return false; } @Override public ConfigAccessor getConfigAccessor() { // TODO Auto-generated method stub return null; } @Override public void startTimerTasks() { // TODO Auto-generated method stub } @Override public void stopTimerTasks() { // TODO Auto-generated method stub } @Override public HelixDataAccessor getHelixDataAccessor() { return accessor; } @Override public void addPreConnectCallback(PreConnectCallback callback) { // TODO Auto-generated method stub } @Override public ZkHelixPropertyStore<ZNRecord> getHelixPropertyStore() { // TODO Auto-generated method stub return null; } @Override public void addInstanceConfigChangeListener(InstanceConfigChangeListener listener) throws Exception { // TODO Auto-generated method stub } @Override public void addInstanceConfigChangeListener(org.apache.helix.InstanceConfigChangeListener listener) throws Exception { } @Override public void addConfigChangeListener(ScopedConfigChangeListener listener, HelixConfigScope.ConfigScopeProperty scope) throws Exception { // TODO Auto-generated method stub } @Override public void addConfigChangeListener(org.apache.helix.ScopedConfigChangeListener listener, HelixConfigScope.ConfigScopeProperty scope) throws Exception { } @Override public void setLiveInstanceInfoProvider(LiveInstanceInfoProvider liveInstanceInfoProvider) { // TODO Auto-generated method stub } @Override public HelixManagerProperties getProperties() { // TODO Auto-generated method stub return _properties; } @Override public void addControllerMessageListener(MessageListener listener) { // TODO Auto-generated method stub } @Override public void addControllerMessageListener(org.apache.helix.MessageListener listener) { } @Override public ParticipantHealthReportCollector getHealthReportCollector() { // TODO Auto-generated method stub return null; } @Override public Long getSessionStartTime() { return 0L; } }
9,692
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/MockZkHelixDataAccessor.java
package org.apache.helix.mock; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.helix.BaseDataAccessor; import org.apache.helix.HelixProperty; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyType; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.manager.zk.ZKHelixDataAccessor; public class MockZkHelixDataAccessor extends ZKHelixDataAccessor { Map<PropertyType, Integer> _readPathCounters = new HashMap<>(); public MockZkHelixDataAccessor(String clusterName, BaseDataAccessor<ZNRecord> baseDataAccessor) { super(clusterName, baseDataAccessor); } @Deprecated @Override public <T extends HelixProperty> List<T> getProperty(List<PropertyKey> keys) { return getProperty(keys, false); } @Override public <T extends HelixProperty> List<T> getProperty(List<PropertyKey> keys, boolean throwException) { for (PropertyKey key : keys) { addCount(key); } return super.getProperty(keys, throwException); } @Override public <T extends HelixProperty> T getProperty(PropertyKey key) { addCount(key); return super.getProperty(key); } @Deprecated @Override public <T extends HelixProperty> Map<String, T> getChildValuesMap(PropertyKey key) { return getChildValuesMap(key, false); } @Override public <T extends HelixProperty> Map<String, T> getChildValuesMap(PropertyKey key, boolean throwException) { Map<String, T> map = super.getChildValuesMap(key, throwException); addCount(key, map.keySet().size()); return map; } private void addCount(PropertyKey key) { addCount(key, 1); } private void addCount(PropertyKey key, int count) { PropertyType type = key.getType(); if (!_readPathCounters.containsKey(type)) { _readPathCounters.put(type, 0); } _readPathCounters.put(type, _readPathCounters.get(type) + count); } public int getReadCount(PropertyType type) { if (_readPathCounters.containsKey(type)) { return _readPathCounters.get(type); } return 0; } public void clearReadCounters() { _readPathCounters.clear(); } }
9,693
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/MockBaseDataAccessor.java
package org.apache.helix.mock; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.helix.BaseDataAccessor; import org.apache.helix.HelixException; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.zkclient.DataUpdater; import org.apache.helix.zookeeper.zkclient.IZkChildListener; import org.apache.helix.zookeeper.zkclient.IZkDataListener; import org.apache.zookeeper.data.Stat; public class MockBaseDataAccessor implements BaseDataAccessor<ZNRecord> { class ZNode { private ZNRecord _record; private Stat _stat; public ZNode (ZNRecord record) { _record = record; _stat = new Stat(); _stat.setCtime(System.currentTimeMillis()); } public void set (ZNRecord record) { _record = record; _stat.setMtime(System.currentTimeMillis()); _stat.setVersion(_stat.getVersion() + 1); } public ZNRecord getRecord() { return _record; } public Stat getStat() { return _stat; } } Map<String, ZNode> _recordMap = new HashMap<>(); @Override public boolean create(String path, ZNRecord record, int options) { return set(path, record, options); } @Override public boolean create(String path, ZNRecord record, int options, long ttl) { return set(path, record, options); } @Override public boolean set(String path, ZNRecord record, int options) { ZNode zNode = _recordMap.get(path); if (zNode == null) { _recordMap.put(path, new ZNode(record)); } else { zNode.set(record); _recordMap.put(path, zNode); } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override public boolean update(String path, DataUpdater<ZNRecord> updater, int options) { ZNode zNode = _recordMap.get(path); ZNRecord current = zNode != null ? zNode.getRecord() : null; ZNRecord newRecord = updater.update(current); if (newRecord != null) { return set(path, newRecord, options); } return false; } @Override public boolean remove(String path, int options) { _recordMap.remove(path); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override public boolean[] createChildren(List<String> paths, List<ZNRecord> records, int options) { return setChildren(paths, records, options); } @Override public boolean[] createChildren(List<String> paths, List<ZNRecord> records, int options, long ttl) { return setChildren(paths, records, options); } @Override public boolean[] setChildren(List<String> paths, List<ZNRecord> records, int options) { boolean [] ret = new boolean[paths.size()]; for (int i = 0; i < paths.size(); i++) { boolean success = create(paths.get(i), records.get(i), options); ret[i] = success; } return ret; } @Override public boolean[] updateChildren(List<String> paths, List<DataUpdater<ZNRecord>> updaters, int options) { boolean [] ret = new boolean[paths.size()]; for (int i = 0; i < paths.size(); i++) { boolean success = update(paths.get(i), updaters.get(i), options); ret[i] = success; } return ret; } @Override public boolean[] remove(List<String> paths, int options) { boolean [] ret = new boolean[paths.size()]; for (int i = 0; i < paths.size(); i++) { boolean success = remove(paths.get(i), options); ret[i] = success; } return ret; } @Override public ZNRecord get(String path, Stat stat, int options) { ZNode zNode = _recordMap.get(path); return zNode != null ? zNode.getRecord() : null; } @Deprecated @Override public List<ZNRecord> get(List<String> paths, List<Stat> stats, int options) { return get(paths, stats, options, false); } @Override public List<ZNRecord> get(List<String> paths, List<Stat> stats, int options, boolean throwException) throws HelixException { List<ZNRecord> records = new ArrayList<>(); for (int i = 0; i < paths.size(); i++) { ZNRecord record = get(paths.get(i), stats.get(i), options); records.add(record); } return records; } @Deprecated @Override public List<ZNRecord> getChildren(String parentPath, List<Stat> stats, int options) { return getChildren(parentPath, stats, options, 0, 0); } @Override public List<ZNRecord> getChildren(String parentPath, List<Stat> stats, int options, int retryCount, int retryInterval) throws HelixException { List<ZNRecord> children = new ArrayList<>(); for (String key : _recordMap.keySet()) { if (key.startsWith(parentPath)) { String[] keySplit = key.split("\\/"); String[] pathSplit = parentPath.split("\\/"); if (keySplit.length - pathSplit.length == 1) { ZNode zNode = _recordMap.get(key); ZNRecord record = zNode != null ? zNode.getRecord() : null; if (record != null) { children.add(record); } } else { System.out.println("keySplit:" + Arrays.toString(keySplit)); System.out.println("pathSplit:" + Arrays.toString(pathSplit)); } } } return children; } @Override public List<String> getChildNames(String parentPath, int options) { List<String> child = new ArrayList<>(); for (String key : _recordMap.keySet()) { if (key.startsWith(parentPath)) { String[] keySplit = key.split("\\/"); String[] pathSplit = parentPath.split("\\/"); if (keySplit.length > pathSplit.length) { child.add(keySplit[pathSplit.length]); } } } return child; } @Override public boolean exists(String path, int options) { return _recordMap.containsKey(path); } @Override public boolean[] exists(List<String> paths, int options) { boolean [] ret = new boolean[paths.size()]; for (int i = 0; i < paths.size(); i++) { ret[i] = _recordMap.containsKey(paths.get(i)); } return ret; } @Override public Stat[] getStats(List<String> paths, int options) { Stat [] stats = new Stat[paths.size()]; for (int i = 0; i < paths.size(); i++) { stats[i] = getStat(paths.get(i), options); } return stats; } @Override public Stat getStat(String path, int options) { ZNode zNode = _recordMap.get(path); return zNode != null ? zNode.getStat() : null; } @Override public void subscribeDataChanges(String path, IZkDataListener listener) { // TODO Auto-generated method stub } @Override public void unsubscribeDataChanges(String path, IZkDataListener listener) { // TODO Auto-generated method stub } @Override public List<String> subscribeChildChanges(String path, IZkChildListener listener) { // TODO Auto-generated method stub return null; } @Override public void unsubscribeChildChanges(String path, IZkChildListener listener) { // TODO Auto-generated method stub } @Override public void reset() { _recordMap.clear(); } @Override public void close() { } @Override public boolean set(String path, ZNRecord record, int options, int expectVersion) { return set(path, record, options); } }
9,694
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/MockClusterMessagingService.java
package org.apache.helix.mock; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import java.util.Map; import org.apache.helix.ClusterMessagingService; import org.apache.helix.Criteria; import org.apache.helix.InstanceType; import org.apache.helix.messaging.AsyncCallback; import org.apache.helix.messaging.handling.MessageHandlerFactory; import org.apache.helix.model.Message; public class MockClusterMessagingService implements ClusterMessagingService { @Override public int send(Criteria recipientCriteria, Message message) { // TODO Auto-generated method stub return 0; } @Override public int send(Criteria receipientCriteria, Message message, AsyncCallback callbackOnReply, int timeOut) { // TODO Auto-generated method stub return 0; } @Override public int sendAndWait(Criteria receipientCriteria, Message message, AsyncCallback callbackOnReply, int timeOut) { // TODO Auto-generated method stub return 0; } @Override public void registerMessageHandlerFactory(String type, MessageHandlerFactory factory) { // TODO Auto-generated method stub } @Override public void registerMessageHandlerFactory(List<String> types, MessageHandlerFactory factory) { // TODO Auto-generated method stub } @Override public int send(Criteria receipientCriteria, Message message, AsyncCallback callbackOnReply, int timeOut, int retryCount) { // TODO Auto-generated method stub return 0; } @Override public int sendAndWait(Criteria receipientCriteria, Message message, AsyncCallback callbackOnReply, int timeOut, int retryCount) { // TODO Auto-generated method stub return 0; } @Override public Map<InstanceType, List<Message>> generateMessage(Criteria recipientCriteria, Message messageTemplate) { // TODO Auto-generated method stub return null; } }
9,695
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/participant/MockMSModelFactory.java
package org.apache.helix.mock.participant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.participant.statemachine.StateModelFactory; // mock master slave state model factory public class MockMSModelFactory extends StateModelFactory<MockMSStateModel> { private MockTransition _transition; public MockMSModelFactory() { this(null); } public MockMSModelFactory(MockTransition transition) { _transition = transition; } public void setTrasition(MockTransition transition) { _transition = transition; // set existing transition for (String resource : getResourceSet()) { for (String partition : getPartitionSet(resource)) { MockMSStateModel stateModel = getStateModel(resource, partition); stateModel.setTransition(transition); } } } @Override public MockMSStateModel createNewStateModel(String resourceName, String partitionKey) { MockMSStateModel model = new MockMSStateModel(_transition); return model; } }
9,696
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/participant/MockTransition.java
package org.apache.helix.mock.participant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.NotificationContext; import org.apache.helix.model.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MockTransition { private static Logger LOG = LoggerFactory.getLogger(MockTransition.class); // called by state model transition functions public void doTransition(Message message, NotificationContext context) throws InterruptedException { LOG.info("default doTransition() invoked"); } // called by state model reset function public void doReset() { LOG.info("default doReset() invoked"); } }
9,697
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/participant/MockMSStateModel.java
package org.apache.helix.mock.participant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.NotificationContext; import org.apache.helix.model.Message; import org.apache.helix.participant.statemachine.StateModel; import org.apache.helix.participant.statemachine.StateModelInfo; import org.apache.helix.participant.statemachine.Transition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // mock master-slave state model @StateModelInfo(initialState = "OFFLINE", states = { "MASTER", "SLAVE", "ERROR" }) public class MockMSStateModel extends StateModel { private static Logger LOG = LoggerFactory.getLogger(MockMSStateModel.class); protected MockTransition _transition; public MockMSStateModel(MockTransition transition) { _transition = transition; } public void setTransition(MockTransition transition) { _transition = transition; } @Transition(to = "*", from = "*") public void generalTransitionHandle(Message message, NotificationContext context) throws InterruptedException { LOG.info(String .format("Resource %s partition %s becomes %s from %s", message.getResourceName(), message.getPartitionName(), message.getToState(), message.getFromState())); if (_transition != null) { _transition.doTransition(message, context); } } @Override public void reset() { LOG.info("Default MockMSStateModel.reset() invoked"); if (_transition != null) { _transition.doReset(); } } }
9,698
0
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock
Create_ds/helix/helix-core/src/test/java/org/apache/helix/mock/participant/MockSchemataModelFactory.java
package org.apache.helix.mock.participant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.helix.participant.statemachine.StateModelFactory; // mock STORAGE_DEFAULT_SM_SCHEMATA state model factory public class MockSchemataModelFactory extends StateModelFactory<MockSchemataStateModel> { @Override public MockSchemataStateModel createNewStateModel(String resourceName, String partitionKey) { MockSchemataStateModel model = new MockSchemataStateModel(); return model; } }
9,699