Package org.apache.helix.model

Examples of org.apache.helix.model.Partition


    // Based on state matches, add eligible instances
    Set<String> eligibleInstances = Sets.newHashSet();
    Set<String> targetStates = jobCfg.getTargetPartitionStates();
    for (String partition : partitions) {
      Map<String, String> stateMap =
          currStateOutput.getCurrentStateMap(targetResource, new Partition(partition));
      Map<String, String> pendingStateMap =
          currStateOutput.getPendingStateMap(targetResource, new Partition(partition));
      for (Map.Entry<String, String> e : stateMap.entrySet()) {
        String instanceName = e.getKey();
        String state = e.getValue();
        String pending = pendingStateMap.get(instanceName);
        if (pending != null) {
View Full Code Here


    Message msg =
        createMessage(MessageType.STATE_TRANSITION, "msgId-001", "OFFLINE", "SLAVE", "TestDB",
            "localhost_0");
    selectMessages.add(msg);

    msgSelectOutput.addMessages("TestDB", new Partition("TestDB_0"), selectMessages);
    event.addAttribute(AttributeName.MESSAGES_SELECTED.toString(), msgSelectOutput);

    runStage(event, throttleStage);

    MessageThrottleStageOutput msgThrottleOutput =
        event.getAttribute(AttributeName.MESSAGES_THROTTLE.toString());
    Assert.assertEquals(msgThrottleOutput.getMessages("TestDB", new Partition("TestDB_0")).size(),
        1);

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

  }
View Full Code Here

    selectMessages.add(msg3);
    selectMessages.add(msg4);
    selectMessages.add(msg5); // should be throttled
    selectMessages.add(msg6); // should be throttled

    msgSelectOutput.addMessages("TestDB", new Partition("TestDB_0"), selectMessages);
    event.addAttribute(AttributeName.MESSAGES_SELECTED.toString(), msgSelectOutput);

    runStage(event, throttleStage);

    MessageThrottleStageOutput msgThrottleOutput =
        event.getAttribute(AttributeName.MESSAGES_THROTTLE.toString());
    List<Message> throttleMessages =
        msgThrottleOutput.getMessages("TestDB", new Partition("TestDB_0"));
    Assert.assertEquals(throttleMessages.size(), 4);
    Assert.assertTrue(throttleMessages.contains(msg1));
    Assert.assertTrue(throttleMessages.contains(msg2));
    Assert.assertTrue(throttleMessages.contains(msg3));
    Assert.assertTrue(throttleMessages.contains(msg4));
View Full Code Here

      for (int pId : pSet) {
        final String pName = pName(jobResource, pId);

        // Check for pending state transitions on this (partition, instance).
        String pendingState =
            currStateOutput.getPendingState(jobResource, new Partition(pName), instance);
        if (pendingState != null) {
          // There is a pending state transition for this (partition, instance). Just copy forward
          // the state assignment from the previous ideal state.
          Map<String, String> stateMap = prevAssignment.getReplicaMap(new Partition(pName));
          if (stateMap != null) {
            String prevState = stateMap.get(instance);
            paMap.put(pId, new PartitionAssignment(instance, prevState));
            assignedPartitions.add(pId);
            LOG.debug(String
                .format(
                    "Task partition %s has a pending state transition on instance %s. Using the previous ideal state which was %s.",
                    pName, instance, prevState));
          }

          continue;
        }

        TaskPartitionState currState =
            TaskPartitionState.valueOf(currStateOutput.getCurrentState(jobResource, new Partition(
                pName), instance));
        jobCtx.setPartitionState(pId, currState);

        // Process any requested state transitions.
        String requestedStateStr =
            currStateOutput.getRequestedState(jobResource, new Partition(pName), instance);
        if (requestedStateStr != null && !requestedStateStr.isEmpty()) {
          TaskPartitionState requestedState = TaskPartitionState.valueOf(requestedStateStr);
          if (requestedState.equals(currState)) {
            LOG.warn(String.format(
                "Requested state %s is the same as the current state for instance %s.",
                requestedState, instance));
          }

          paMap.put(pId, new PartitionAssignment(instance, requestedState.name()));
          assignedPartitions.add(pId);
          LOG.debug(String.format(
              "Instance %s requested a state transition to %s for partition %s.", instance,
              requestedState, pName));
          continue;
        }

        switch (currState) {
        case RUNNING:
        case STOPPED: {
          TaskPartitionState nextState;
          if (jobTgtState == TargetState.START) {
            nextState = TaskPartitionState.RUNNING;
          } else {
            nextState = TaskPartitionState.STOPPED;
          }

          paMap.put(pId, new PartitionAssignment(instance, nextState.name()));
          assignedPartitions.add(pId);
          LOG.debug(String.format("Setting task partition %s state to %s on instance %s.", pName,
              nextState, instance));
        }
          break;
        case COMPLETED: {
          // The task has completed on this partition. Mark as such in the context object.
          donePartitions.add(pId);
          LOG.debug(String
              .format(
                  "Task partition %s has completed with state %s. Marking as such in rebalancer context.",
                  pName, currState));
          partitionsToDropFromIs.add(pId);
          markPartitionCompleted(jobCtx, pId);
        }
          break;
        case TIMED_OUT:
        case TASK_ERROR:
        case ERROR: {
          donePartitions.add(pId); // The task may be rescheduled on a different instance.
          LOG.debug(String.format(
              "Task partition %s has error state %s. Marking as such in rebalancer context.",
              pName, currState));
          markPartitionError(jobCtx, pId, currState, true);
          // The error policy is to fail the task as soon a single partition fails for a specified
          // maximum number of attempts.
          if (jobCtx.getPartitionNumAttempts(pId) >= jobCfg.getMaxAttemptsPerTask()) {
            // If the user does not require this task to succeed in order for the job to succeed,
            // then we don't have to fail the job right now
            boolean successOptional = false;
            String taskId = jobCtx.getTaskIdForPartition(pId);
            if (taskId != null) {
              TaskConfig taskConfig = jobCfg.getTaskConfig(taskId);
              if (taskConfig != null) {
                successOptional = taskConfig.isSuccessOptional();
              }
            }

            // Similarly, if we have some leeway for how many tasks we can fail, then we don't have
            // to fail the job immediately
            if (skippedPartitions.size() < jobCfg.getFailureThreshold()) {
              successOptional = true;
            }

            if (!successOptional) {
              long finishTime = currentTime;
              workflowCtx.setJobState(jobResource, TaskState.FAILED);
              if (workflowConfig.isTerminable()) {
                workflowCtx.setWorkflowState(TaskState.FAILED);
                workflowCtx.setFinishTime(finishTime);
              }
              jobCtx.setFinishTime(finishTime);
              markAllPartitionsError(jobCtx, currState, false);
              addAllPartitions(allPartitions, partitionsToDropFromIs);
              return emptyAssignment(jobResource, currStateOutput);
            } else {
              skippedPartitions.add(pId);
              partitionsToDropFromIs.add(pId);
            }
          } else {
            // Mark the task to be started at some later time (if enabled)
            markPartitionDelayed(jobCfg, jobCtx, pId);
          }
        }
          break;
        case INIT:
        case DROPPED: {
          // currState in [INIT, DROPPED]. Do nothing, the partition is eligible to be reassigned.
          donePartitions.add(pId);
          LOG.debug(String.format(
              "Task partition %s has state %s. It will be dropped from the current ideal state.",
              pName, currState));
        }
          break;
        default:
          throw new AssertionError("Unknown enum symbol: " + currState);
        }
      }

      // Remove the set of task partitions that are completed or in one of the error states.
      pSet.removeAll(donePartitions);
    }

    // For delayed tasks, trigger a rebalance event for the closest upcoming ready time
    scheduleForNextTask(jobResource, jobCtx, currentTime);

    if (isJobComplete(jobCtx, allPartitions, skippedPartitions)) {
      workflowCtx.setJobState(jobResource, TaskState.COMPLETED);
      jobCtx.setFinishTime(currentTime);
      if (isWorkflowComplete(workflowCtx, workflowConfig)) {
        workflowCtx.setWorkflowState(TaskState.COMPLETED);
        workflowCtx.setFinishTime(currentTime);
      }
    }

    // Make additional task assignments if needed.
    if (jobTgtState == TargetState.START) {
      // Contains the set of task partitions that must be excluded from consideration when making
      // any new assignments.
      // This includes all completed, failed, delayed, and already assigned partitions.
      Set<Integer> excludeSet = Sets.newTreeSet(assignedPartitions);
      addCompletedPartitions(excludeSet, jobCtx, allPartitions);
      excludeSet.addAll(skippedPartitions);
      excludeSet.addAll(getNonReadyPartitions(jobCtx, currentTime));
      // Get instance->[partition, ...] mappings for the target resource.
      Map<String, SortedSet<Integer>> tgtPartitionAssignments =
          getTaskAssignment(currStateOutput, prevAssignment, liveInstances, jobCfg, jobCtx,
              workflowConfig, workflowCtx, allPartitions, cache);
      for (Map.Entry<String, SortedSet<Integer>> entry : taskAssignments.entrySet()) {
        String instance = entry.getKey();
        if (!tgtPartitionAssignments.containsKey(instance)) {
          continue;
        }
        // Contains the set of task partitions currently assigned to the instance.
        Set<Integer> pSet = entry.getValue();
        int numToAssign = jobCfg.getNumConcurrentTasksPerInstance() - pSet.size();
        if (numToAssign > 0) {
          List<Integer> nextPartitions =
              getNextPartitions(tgtPartitionAssignments.get(instance), excludeSet, numToAssign);
          for (Integer pId : nextPartitions) {
            String pName = pName(jobResource, pId);
            paMap.put(pId, new PartitionAssignment(instance, TaskPartitionState.RUNNING.name()));
            excludeSet.add(pId);
            jobCtx.setAssignedParticipant(pId, instance);
            jobCtx.setPartitionState(pId, TaskPartitionState.INIT);
            LOG.debug(String.format("Setting task partition %s state to %s on instance %s.", pName,
                TaskPartitionState.RUNNING, instance));
          }
        }
      }
    }

    // Construct a ResourceAssignment object from the map of partition assignments.
    ResourceAssignment ra = new ResourceAssignment(jobResource);
    for (Map.Entry<Integer, PartitionAssignment> e : paMap.entrySet()) {
      PartitionAssignment pa = e.getValue();
      ra.addReplicaMap(new Partition(pName(jobResource, e.getKey())),
          ImmutableMap.of(pa._instance, pa._state));
    }

    return ra;
  }
View Full Code Here

      }
      int pId = partitions.get(0);
      if (includeSet.contains(pId)) {
        for (String instance : instances) {
          String pending =
              currStateOutput.getPendingState(tgtIs.getResourceName(), new Partition(pName),
                  instance);
          if (pending != null) {
            continue;
          }
          String s =
              currStateOutput.getCurrentState(tgtIs.getResourceName(), new Partition(pName),
                  instance);
          String state = (s == null ? null : s.toString());
          if (tgtStates == null || tgtStates.contains(state)) {
            result.get(instance).add(pId);
          }
View Full Code Here

      Assert.fail("Fail to register ClusterStatusMonitor");
    }

    // Test #setPerInstanceResourceStatus()
    BestPossibleStateOutput bestPossibleStates = new BestPossibleStateOutput();
    bestPossibleStates.setState(testDB, new Partition(testDB_0), "localhost_12918", "MASTER");
    bestPossibleStates.setState(testDB, new Partition(testDB_0), "localhost_12919", "SLAVE");
    bestPossibleStates.setState(testDB, new Partition(testDB_0), "localhost_12920", "SLAVE");
    bestPossibleStates.setState(testDB, new Partition(testDB_0), "localhost_12921", "OFFLINE");
    bestPossibleStates.setState(testDB, new Partition(testDB_0), "localhost_12922", "DROPPED");

    Map<String, InstanceConfig> instanceConfigMap = Maps.newHashMap();
    for (int i = 0; i < n; i++) {
      String instanceName = "localhost_" + (12918 + i);
      InstanceConfig config = new InstanceConfig(instanceName);
      instanceConfigMap.put(instanceName, config);
    }

    Map<String, Resource> resourceMap = Maps.newHashMap();
    Resource db = new Resource(testDB);
    db.setStateModelDefRef("MasterSlave");
    db.addPartition(testDB_0);
    resourceMap.put(testDB, db);

    Map<String, StateModelDefinition> stateModelDefMap = Maps.newHashMap();
    StateModelDefinition msStateModelDef =
        new StateModelDefinition(StateModelConfigGenerator.generateConfigForMasterSlave());
    stateModelDefMap.put("MasterSlave", msStateModelDef);

    monitor.setPerInstanceResourceStatus(bestPossibleStates, instanceConfigMap, resourceMap,
        stateModelDefMap);

    // localhost_12918 should have 1 partition because it's MASTER
    ObjectName objName =
        monitor.getObjectName(monitor.getPerInstanceResourceBeanName("localhost_12918", testDB));
    Object value = _server.getAttribute(objName, "PartitionGauge");
    Assert.assertTrue(value instanceof Long);
    Assert.assertEquals((Long) value, new Long(1));
    value = _server.getAttribute(objName, "SensorName");
    Assert.assertTrue(value instanceof String);
    Assert.assertEquals((String) value, String.format("%s.%s.%s.%s.%s",
        ClusterStatusMonitor.PARTICIPANT_STATUS_KEY, clusterName, ClusterStatusMonitor.DEFAULT_TAG,
        "localhost_12918", testDB));

    // localhost_12919 should have 1 partition because it's SLAVE
    objName =
        monitor.getObjectName(monitor.getPerInstanceResourceBeanName("localhost_12919", testDB));
    value = _server.getAttribute(objName, "PartitionGauge");
    Assert.assertTrue(value instanceof Long);
    Assert.assertEquals((Long) value, new Long(1));

    // localhost_12921 should have 0 partition because it's OFFLINE
    objName =
        monitor.getObjectName(monitor.getPerInstanceResourceBeanName("localhost_12921", testDB));
    value = _server.getAttribute(objName, "PartitionGauge");
    Assert.assertTrue(value instanceof Long);
    Assert.assertEquals((Long) value, new Long(0));

    // localhost_12922 should have 0 partition because it's DROPPED
    objName =
        monitor.getObjectName(monitor.getPerInstanceResourceBeanName("localhost_12922", testDB));
    value = _server.getAttribute(objName, "PartitionGauge");
    Assert.assertTrue(value instanceof Long);
    Assert.assertEquals((Long) value, new Long(0));

    // Missing localhost_12918 in best possible ideal-state should remove it from mbean
    bestPossibleStates.getInstanceStateMap(testDB, new Partition(testDB_0)).remove(
        "localhost_12918");
    monitor.setPerInstanceResourceStatus(bestPossibleStates, instanceConfigMap, resourceMap,
        stateModelDefMap);
    try {
      objName =
View Full Code Here

            String instanceName = partErrStates.get(partitionName);

            if (!bestPossStateMap.containsKey(resourceName)) {
              bestPossStateMap.put(resourceName, new HashMap<Partition, Map<String, String>>());
            }
            Partition partition = new Partition(partitionName);
            if (!bestPossStateMap.get(resourceName).containsKey(partition)) {
              bestPossStateMap.get(resourceName).put(partition, new HashMap<String, String>());
            }
            bestPossStateMap.get(resourceName).get(partition)
                .put(instanceName, HelixDefinedState.ERROR.toString());
          }
        }
      }

      // System.out.println("stateMap: " + bestPossStateMap);

      for (String resourceName : idealStates.keySet()) {
        ExternalView extView = extViews.get(resourceName);
        if (extView == null) {
          LOG.info("externalView for " + resourceName + " is not available");
          return false;
        }

        // step 0: remove empty map and DROPPED state from best possible state
        Map<Partition, Map<String, String>> bpStateMap =
            bestPossOutput.getResourceMap(resourceName);
        Iterator<Entry<Partition, Map<String, String>>> iter = bpStateMap.entrySet().iterator();
        while (iter.hasNext()) {
          Map.Entry<Partition, Map<String, String>> entry = iter.next();
          Map<String, String> instanceStateMap = entry.getValue();
          if (instanceStateMap.isEmpty()) {
            iter.remove();
          } else {
            // remove instances with DROPPED state
            Iterator<Map.Entry<String, String>> insIter = instanceStateMap.entrySet().iterator();
            while (insIter.hasNext()) {
              Map.Entry<String, String> insEntry = insIter.next();
              String state = insEntry.getValue();
              if (state.equalsIgnoreCase(HelixDefinedState.DROPPED.toString())) {
                insIter.remove();
              }
            }
          }
        }

        // System.err.println("resource: " + resourceName + ", bpStateMap: " + bpStateMap);

        // step 1: externalView and bestPossibleState has equal size
        int extViewSize = extView.getRecord().getMapFields().size();
        int bestPossStateSize = bestPossOutput.getResourceMap(resourceName).size();
        if (extViewSize != bestPossStateSize) {
          LOG.info("exterView size (" + extViewSize + ") is different from bestPossState size ("
              + bestPossStateSize + ") for resource: " + resourceName);

          // System.err.println("exterView size (" + extViewSize
          // + ") is different from bestPossState size (" + bestPossStateSize
          // + ") for resource: " + resourceName);
          // System.out.println("extView: " + extView.getRecord().getMapFields());
          // System.out.println("bestPossState: " +
          // bestPossOutput.getResourceMap(resourceName));
          return false;
        }

        // step 2: every entry in external view is contained in best possible state
        for (String partition : extView.getRecord().getMapFields().keySet()) {
          Map<String, String> evInstanceStateMap = extView.getRecord().getMapField(partition);
          Map<String, String> bpInstanceStateMap =
              bestPossOutput.getInstanceStateMap(resourceName, new Partition(partition));

          boolean result =
              ClusterStateVerifier.<String, String> compareMap(evInstanceStateMap,
                  bpInstanceStateMap);
          if (result == false) {
View Full Code Here

          continue;
        }

        if (!message.getBatchMessageMode()) {
          String partitionName = message.getPartitionName();
          Partition partition = resource.getPartition(partitionName);
          if (partition != null) {
            currentStateOutput.setPendingState(resourceName, partition, instanceName,
                message.getToState());
          } else {
            // log
          }
        } else {
          List<String> partitionNames = message.getPartitionNames();
          if (!partitionNames.isEmpty()) {
            for (String partitionName : partitionNames) {
              Partition partition = resource.getPartition(partitionName);
              if (partition != null) {
                currentStateOutput.setPendingState(resourceName, partition, instanceName,
                    message.getToState());
              } else {
                // log
              }
            }
          }
        }
      }
    }
    for (LiveInstance instance : liveInstances.values()) {
      String instanceName = instance.getInstanceName();

      String clientSessionId = instance.getSessionId();
      Map<String, CurrentState> currentStateMap =
          cache.getCurrentState(instanceName, clientSessionId);
      for (CurrentState currentState : currentStateMap.values()) {

        if (!instance.getSessionId().equals(currentState.getSessionId())) {
          continue;
        }
        String resourceName = currentState.getResourceName();
        String stateModelDefName = currentState.getStateModelDefRef();
        Resource resource = resourceMap.get(resourceName);
        if (resource == null) {
          continue;
        }
        if (stateModelDefName != null) {
          currentStateOutput.setResourceStateModelDef(resourceName, stateModelDefName);
        }

        currentStateOutput.setBucketSize(resourceName, currentState.getBucketSize());

        Map<String, String> partitionStateMap = currentState.getPartitionStateMap();
        for (String partitionName : partitionStateMap.keySet()) {
          Partition partition = resource.getPartition(partitionName);
          if (partition != null) {
            currentStateOutput.setCurrentState(resourceName,
                                               partition,
                                               instanceName,
                                               currentState.getState(partitionName));
View Full Code Here

    Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();

    for (String partition : partitions) {
      Map<String, String> curStateMap =
          currentStateOutput.getCurrentStateMap(resourceName, new Partition(partition));
      map.put(partition, new HashMap<String, String>());
      for (String node : curStateMap.keySet()) {
        String state = curStateMap.get(node);
        map.get(partition).put(node, state);
      }

      Map<String, String> pendingStateMap =
          currentStateOutput.getPendingStateMap(resourceName, new Partition(partition));
      for (String node : pendingStateMap.keySet()) {
        String state = pendingStateMap.get(node);
        map.get(partition).put(node, state);
      }
    }
View Full Code Here

                      "SLAVE",
                      "TestDB",
                      "localhost_0");
    selectMessages.add(msg);

    msgSelectOutput.addMessages("TestDB", new Partition("TestDB_0"), selectMessages);
    event.addAttribute(AttributeName.MESSAGES_SELECTED.toString(), msgSelectOutput);

    runStage(event, throttleStage);

    MessageThrottleStageOutput msgThrottleOutput =
        event.getAttribute(AttributeName.MESSAGES_THROTTLE.toString());
    Assert.assertEquals(msgThrottleOutput.getMessages("TestDB", new Partition("TestDB_0"))
                                         .size(),
                        1);

    System.out.println("END " + clusterName + " at "
        + new Date(System.currentTimeMillis()));
View Full Code Here

TOP

Related Classes of org.apache.helix.model.Partition

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.