Java Code Examples for org.apache.mesos.Protos

The following examples show how to use org.apache.mesos.Protos. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testResourceOfferContainerForAuxServiceWithOutRole() {
  Protos.Offer offer = new OfferBuilder("test.com")
      .addScalarResource("cpus", 2.0)
      .addScalarResource("mem", 8000)
      .addRangeResource("ports", 3500, 3600)
      .build();
  Map<String, Long> ports = new HashMap<>(4);
  ports.put("test1.address", 0L);
  ports.put("test2.address", 0L);
  ports.put("test3.address", 0L);
  ports.put("test4.port", 3501L);
  ServiceResourceProfile profile = new ServiceResourceProfile("jobhistory", 2.0, 8000.0, ports);
  ResourceOfferContainer roc = new ResourceOfferContainer(offer, profile, null);
  assertTrue(roc.getHostName().equals("test.com"));
  assertTrue("Should be satisfied if offer contains request", roc.satisfies(profile));
}
 
Example 2
Source Project: elasticsearch   Source File: TaskInfoFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Protos.CommandInfo nativeCommand(Configuration configuration, List<String> args, Long elasticSearchNodeId) {
    String address = configuration.getFrameworkFileServerAddress();
    if (address == null) {
        throw new NullPointerException("Webserver address is null");
    }
    String httpPath = address + "/get/" + Configuration.ES_TAR;
    String command = configuration.nativeCommand(args);
    final Protos.Environment environment = Protos.Environment.newBuilder().addAllVariables(new ExecutorEnvironmentalVariables(configuration, elasticSearchNodeId).getList()).build();
    final Protos.CommandInfo.Builder builder = Protos.CommandInfo.newBuilder()
            .setShell(true)
            .setValue(command)
            .setUser("root")
            .mergeEnvironment(environment);
    if (configuration.getElasticsearchBinary().isEmpty()) {
        builder.addUris(Protos.CommandInfo.URI.newBuilder().setValue(httpPath));
    } else {
        builder.addUris(Protos.CommandInfo.URI.newBuilder().setValue(configuration.getElasticsearchBinary()));
    }
    if (!configuration.getElasticsearchSettingsLocation().isEmpty()) {
        builder.addUris(Protos.CommandInfo.URI.newBuilder().setValue(configuration.getElasticsearchSettingsLocation()));
    }
    return builder
            .build();
}
 
Example 3
Source Project: dcos-commons   Source File: StateStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeatedStoreStatus() throws Exception {
    Protos.TaskInfo task = createTask(TestConstants.TASK_NAME);
    store.storeTasks(Arrays.asList(task));

    // taskstatus id must exactly match taskinfo id:
    Protos.TaskStatus status = TASK_STATUS.toBuilder().setTaskId(task.getTaskId()).build();
    store.storeStatus(TestConstants.TASK_NAME, status);
    assertEquals(status, store.fetchStatus(TestConstants.TASK_NAME).get());

    store.storeStatus(TestConstants.TASK_NAME, status);
    assertEquals(status, store.fetchStatus(TestConstants.TASK_NAME).get());

    assertEquals(Arrays.asList(TestConstants.TASK_NAME), store.fetchTaskNames());
    Collection<Protos.TaskStatus> statuses = store.fetchStatuses();
    assertEquals(1, statuses.size());
    assertEquals(status, statuses.iterator().next());
}
 
Example 4
Source Project: dcos-commons   Source File: PersistentLaunchRecorder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method keeps the resources associated with tasks in the state store up to date, when a task which shares
 * their resource-set is launched.
 *
 * @param podInstance the parent pod associated with the task being launched
 * @param taskInfo    the task being launched
 */
@VisibleForTesting
void updateTaskResourcesWithinResourceSet(PodInstance podInstance, Protos.TaskInfo taskInfo) {
  Optional<TaskSpec> taskSpec = TaskUtils.getTaskSpec(podInstance, taskInfo.getName());
  if (!taskSpec.isPresent()) {
    return;
  }

  // Update any other TaskInfos in this resource set to have the same resources:
  Collection<Protos.TaskInfo> taskInfosWithSameResourceSet =
      getOtherTasksInResourceSet(podInstance, taskSpec.get());
  stateStore.storeTasks(updateTasksWithResources(
      taskInfosWithSameResourceSet,
      taskInfo.getResourcesList(),
      taskInfo.hasExecutor() ?
          Optional.of(taskInfo.getExecutor().getResourcesList())
          : Optional.empty()));
}
 
Example 5
Source Project: dcos-commons   Source File: MultiServiceEventClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Maps the provided status to the service that owns its task, then queries that service with the status.
 *
 * <p>This is an optimization which avoids querying services about task statuses that don't relate to them.
 * <p>In addition to reducing unnecessary queries, this also improves isolation between services. They only see
 * task statuses which relate to them.
 */
@Override
public TaskStatusResponse taskStatus(Protos.TaskStatus status) {
  return multiServiceManager
      .getMatchingService(status)
      .map(x -> x.taskStatus(status))
      .orElseGet(() -> multiServiceManager
          .getServiceSanitized(frameworkName)
          .map(x -> {
            LOGGER.info("Forwarding task status to default service: {}", frameworkName);
            return x.taskStatus(status);
          })
          .orElseGet(() -> {
            // Unrecognized service. Status for old task ?
            LOGGER.info("Received status for unknown task {}: {}",
                status.getTaskId().getValue(), TextFormat.shortDebugString(status));
            return TaskStatusResponse.unknownTask();
          })
      );
}
 
Example 6
Source Project: dcos-commons   Source File: DefaultServiceSpecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void validPortResource() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("valid-multiple-ports.yml").getFile());
    DefaultServiceSpec serviceSpec = DefaultServiceSpec.newGenerator(file, SCHEDULER_CONFIG).build();

    List<ResourceSpec> portsResources = serviceSpec.getPods().get(0).getTasks().get(0).getResourceSet()
            .getResources()
            .stream()
            .filter(r -> r.getName().equals("ports"))
            .collect(Collectors.toList());

    Assert.assertEquals(2, portsResources.size());

    Protos.Value.Ranges http = portsResources.get(0).getValue().getRanges();
    Protos.Value.Ranges another = portsResources.get(1).getValue().getRanges();
    Assert.assertEquals(1, http.getRangeCount());
    Assert.assertEquals(1, another.getRangeCount());
    Assert.assertEquals(8080, http.getRange(0).getBegin(), http.getRange(0).getEnd());
    Assert.assertEquals(8088, another.getRange(0).getBegin(), another.getRange(0).getEnd());
}
 
Example 7
Source Project: flink   Source File: ZooKeeperMesosWorkerStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean removeWorker(Protos.TaskID taskID) throws Exception {
	checkNotNull(taskID, "taskID");
	String path = getPathForWorker(taskID);
	synchronized (startStopLock) {
		verifyIsRunning();

		if (workersInZooKeeper.exists(path) == -1) {
			LOG.debug("No such worker {} in ZooKeeper.", taskID);
			return false;
		}

		workersInZooKeeper.releaseAndTryRemove(path);
		LOG.debug("Removed worker {} from ZooKeeper.", taskID);
		return true;
	}
}
 
Example 8
Source Project: dcos-commons   Source File: ResourceTestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Protos.Resource getReservedRootVolume(double diskSize, String resourceId, String persistenceId, String frameworkId) {
    VolumeSpec volumeSpec = DefaultVolumeSpec.createRootVolume(
            diskSize,
            TestConstants.CONTAINER_PATH,
            TestConstants.ROLE,
            Constants.ANY_ROLE,
            TestConstants.PRINCIPAL);
    return ResourceBuilder.fromSpec(
            volumeSpec,
            Optional.of(resourceId),
            Optional.empty(),
            Optional.of(persistenceId),
            Optional.empty(),
            Optional.empty(),
            Optional.of(frameworkId))
            .build();
}
 
Example 9
Source Project: Flink-CEPplus   Source File: MesosResourceManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test Mesos registration handling.
 */
@Test
public void testRegistered() throws Exception {
	new Context() {{
		startResourceManager();

		Protos.MasterInfo masterInfo = Protos.MasterInfo.newBuilder()
			.setId("master1").setIp(0).setPort(5050).build();
		resourceManager.registered(new Registered(framework1, masterInfo));

		verify(rmServices.workerStore).setFrameworkID(Option.apply(framework1));
		resourceManager.connectionMonitor.expectMsgClass(Registered.class);
		resourceManager.reconciliationCoordinator.expectMsgClass(Registered.class);
		resourceManager.launchCoordinator.expectMsgClass(Registered.class);
		resourceManager.taskRouter.expectMsgClass(Registered.class);
	}};
}
 
Example 10
Source Project: Singularity   Source File: SingularityExecutorMonitor.java    License: Apache License 2.0 6 votes vote down vote up
private void onFinish(SingularityExecutorTask task, Protos.TaskState taskState) {
  processKiller.cancelDestroyFuture(task.getTaskId());

  tasks.remove(task.getTaskId());
  processRunningTasks.remove(task.getTaskId());
  processBuildingTasks.remove(task.getTaskId());

  task.cleanup(taskState);

  ListeningExecutorService executorService = taskToShellCommandPool.remove(
    task.getTaskId()
  );

  if (executorService != null) {
    executorService.shutdownNow();
    try {
      executorService.awaitTermination(5, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      LOG.warn("Awaiting shutdown of shell executor service", e);
    }
  }

  logging.stopTaskLogger(task.getTaskId(), task.getLogbackLog());

  checkIdleExecutorShutdown(task.getDriver());
}
 
Example 11
Source Project: dcos-commons   Source File: TaskUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTaskInfoWithNoStatusRequiresNoRecovery() throws Exception {
    ConfigStore<ServiceSpec> configStore = newConfigStore(persister);

    Protos.TaskInfo taskInfo = newTaskInfo("name-0-not-present", configStore);

    assertThat(TaskUtils.getTasksNeedingRecovery(configStore, Collections.singleton(taskInfo), Collections.emptyList()),
            is(empty()));
}
 
Example 12
Source Project: dcos-cassandra-service   Source File: BackupUploadTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BackupUploadTask update(Protos.Offer offer) {
    return new BackupUploadTask(getBuilder()
        .setSlaveId(offer.getSlaveId())
        .setData(getData().withHostname(offer.getHostname()).getBytes())
        .build());
}
 
Example 13
Source Project: dcos-cassandra-service   Source File: CassandraState.java    License: Apache License 2.0 5 votes vote down vote up
public CleanupTask createCleanupTask(
        CassandraDaemonTask daemon,
        CleanupContext context) throws PersistenceException {

    Optional<Protos.TaskInfo> template = getTemplate(daemon);

    if (template.isPresent()) {
        return CleanupTask.create(template.get(), daemon, context);
    } else {
        throw new PersistenceException("Failed to retrieve ClusterTask Template.");
    }
}
 
Example 14
Source Project: Flink-CEPplus   Source File: MesosResourceManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a launchable task for Fenzo to process.
 */
private LaunchableMesosWorker createLaunchableMesosWorker(Protos.TaskID taskID) {
	LOG.debug("LaunchableMesosWorker parameters: {}", taskManagerParameters);

	LaunchableMesosWorker launchable =
		new LaunchableMesosWorker(
			artifactServer,
			taskManagerParameters,
			taskManagerContainerSpec,
			taskID,
			mesosConfig);

	return launchable;
}
 
Example 15
@Inject
public SimulatedRemoteMesosSchedulerDriverFactory(@Named(SimulatedRemoteInstanceCloudConnector.SIMULATED_CLOUD) Channel channel, TitusRuntime titusRuntime) {
    this.titusRuntime = titusRuntime;

    this.masterInfo = Protos.MasterInfo.newBuilder()
            .setId("MasterId#Simulated")
            .setAddress(Protos.Address.newBuilder().setHostname("simulated").setPort(0))
            .setHostname("simulated")
            .setIp(0)
            .setPort(0)
            .setVersion("1.2.simulated")
            .build();

    this.channel = channel;
}
 
Example 16
private OfferRequirement getCreateOfferRequirement(String type, Protos.TaskInfo taskInfo) {
    ExecutorInfo execInfo = taskInfo.getExecutor();
    taskInfo = Protos.TaskInfo.newBuilder(taskInfo).clearExecutor().build();

    try {
        return OfferRequirement.create(type, Arrays.asList(taskInfo), Optional.of(execInfo));
    } catch (InvalidRequirementException e) {
        LOGGER.error("Failed to construct OfferRequirement with Exception: ", e);
        return null;
    }
}
 
Example 17
Source Project: dcos-commons   Source File: OfferEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the evaluation stages needed to update the reservations associated with a resource set. In the default
 * case, a resource set is 1:1 with a task, but services may also have multiple tasks that share a single resource
 * set.
 */
private Collection<OfferEvaluationStage> getExistingResourceSetStages(
    PodInstanceRequirement podInstanceRequirement,
    Optional<String> resourceNamespace,
    Map<String, Protos.TaskInfo> allTasksInPod,
    ResourceSet resourceSet,
    Collection<String> taskSpecNamesInResourceSet,
    Optional<String> frameworkId)
{
  // Search for any existing TaskInfo for one of the tasks in this resource set. The TaskInfo should have a copy
  // of the resources assigned to the resource set.
  Collection<String> taskInfoNames = taskSpecNamesInResourceSet.stream()
      .map(taskSpecName ->
          CommonIdUtils.getTaskInstanceName(podInstanceRequirement.getPodInstance(), taskSpecName))
      .collect(Collectors.toList());
  Optional<Protos.TaskInfo> taskInfo = taskInfoNames.stream()
      .map(allTasksInPod::get)
      .filter(Objects::nonNull)
      .findAny();
  if (!taskInfo.isPresent()) {
    // This shouldn't happen, because this codepath is for reevaluating pods that had been launched
    // before. There should always be at least one TaskInfo for the resource set...
    logger.error("Failed to find existing TaskInfo among {}, cannot evaluate existing resource set {}",
        taskInfoNames, resourceSet.getId());
    return Collections.emptyList();
  }

  TaskResourceMapper taskResourceMapper =
      new TaskResourceMapper(taskSpecNamesInResourceSet, resourceSet, taskInfo.get(), resourceNamespace, frameworkId);

  Collection<OfferEvaluationStage> evaluationStages = new ArrayList<>();
  taskResourceMapper.getOrphanedResources()
      .forEach(resource -> evaluationStages.add(new UnreserveEvaluationStage(resource)));
  evaluationStages.addAll(taskResourceMapper.getEvaluationStages());
  return evaluationStages;
}
 
Example 18
Source Project: dcos-commons   Source File: StateStoreUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns an Optional<TaskStatus> from the properties in the provided state store for the
 * specified task name.
 */
public static Optional<Protos.TaskStatus> getTaskStatusFromProperty(StateStore stateStore,
                                                                    String taskName)
{
  try {
    return Optional.of(Protos.TaskStatus.parseFrom(
        stateStore.fetchProperty(taskName + PROPERTY_TASK_INFO_SUFFIX)));
  } catch (Exception e) {
    // Broadly catch exceptions to handle:
    // Invalid TaskStatuses
    // StateStoreExceptions
    LOGGER.error("Unable to decode TaskStatus for taskName=" + taskName, e);
    return Optional.empty();
  }
}
 
Example 19
Source Project: incubator-myriad   Source File: SchedulerState.java    License: Apache License 2.0 5 votes vote down vote up
public Set<Protos.TaskID> getStagingTaskIds() {
  Set<Protos.TaskID> returnSet = new HashSet<>();
  for (Map.Entry<String, SchedulerStateForType> entry : statesForTaskType.entrySet()) {
    returnSet.addAll(entry.getValue().getStagingTaskIds());
  }
  return returnSet;
}
 
Example 20
Source Project: dcos-commons   Source File: DefaultSchedulerTest.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Protos.Resource> getExpectedResources(Collection<OfferRecommendation> operations) {
    for (OfferRecommendation operation : operations) {
        if (operation.getOperation().get().getType().equals(Offer.Operation.Type.LAUNCH_GROUP)) {
            return Stream.concat(
                            operation.getOperation().get().getLaunchGroup().getTaskGroup().getTasksList().stream()
                                .flatMap(taskInfo -> taskInfo.getResourcesList().stream()),
                            operation.getOperation().get().getLaunchGroup().getExecutor().getResourcesList().stream())
                    .collect(Collectors.toList());
        }
    }

    return Collections.emptyList();
}
 
Example 21
Source Project: Flink-CEPplus   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets a stream of values from a collection of range resources.
 */
public static LongStream rangeValues(Collection<Protos.Resource> resources) {
	checkNotNull(resources);
	return resources.stream()
		.filter(Protos.Resource::hasRanges)
		.flatMap(r -> r.getRanges().getRangeList().stream())
		.flatMapToLong(Utils::rangeValues);
}
 
Example 22
Source Project: dcos-commons   Source File: PodQueriesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReplacePodManyRunning() {
    when(mockStateStore.fetchTasks()).thenReturn(TASK_INFOS);
    when(mockStateStore.fetchStatuses()).thenReturn(TASK_STATUSES);

    String podInstanceName = "test-0";

    Response response = PodQueries.restartPod(
            mockStateStore, mockConfigStore, podInstanceName, RecoveryType.PERMANENT, mockFailureSetter);
    assertEquals(200, response.getStatus());
    JSONObject json = new JSONObject((String) response.getEntity());
    assertEquals(2, json.length());
    assertEquals(podInstanceName, json.getString("pod"));
    assertEquals(4, json.getJSONArray("tasks").length());
    assertEquals(podInstanceName + "-a", json.getJSONArray("tasks").get(0));
    assertEquals(podInstanceName + "-b", json.getJSONArray("tasks").get(1));
    assertEquals(podInstanceName + "-c", json.getJSONArray("tasks").get(2));
    assertEquals(podInstanceName + "-d", json.getJSONArray("tasks").get(3));

    verify(mockDriver).killTask(POD_0_TASK_A.getTaskId());
    verify(mockDriver).killTask(POD_0_TASK_B.getTaskId());
    verify(mockDriver).killTask(POD_0_TASK_C.getTaskId());
    verify(mockDriver).killTask(POD_0_TASK_D.getTaskId());
    verifyNoMoreInteractions(mockDriver);

    List<Protos.TaskInfo> expectedFailedTasks = TASK_INFOS.stream()
            .filter(taskInfo -> taskInfo.getName().startsWith(podInstanceName))
            .collect(Collectors.toList());
    verify(mockFailureSetter, times(1)).setFailure(mockConfigStore, mockStateStore, expectedFailedTasks);
    verifyNoMoreInteractions(mockFailureSetter);
}
 
Example 23
Source Project: dcos-commons   Source File: DefaultResourceSpec.java    License: Apache License 2.0 5 votes vote down vote up
@JsonCreator
protected DefaultResourceSpec(
    @JsonProperty("name") String name,
    @JsonProperty("value") Protos.Value value,
    @JsonProperty("role") String role,
    @JsonProperty("pre-reserved-role") String preReservedRole,
    @JsonProperty("principal") String principal)
{
  this.name = name;
  this.value = value;
  this.role = role;
  this.preReservedRole = preReservedRole == null ? Constants.ANY_ROLE : preReservedRole;
  this.principal = principal;
}
 
Example 24
@Test
public void assertUnknownStatusUpdate() {
    TaskNode taskNode = TaskNode.builder().build();
    schedulerEngine.statusUpdate(null, Protos.TaskStatus.newBuilder()
            .setTaskId(Protos.TaskID.newBuilder().setValue(taskNode.getTaskNodeValue())).setState(Protos.TaskState.TASK_UNKNOWN)
            .setSlaveId(Protos.SlaveID.newBuilder().setValue("slave-S0")).build());
    Mockito.verify(statisticManager).taskRunFailed();
}
 
Example 25
Source Project: Flink-CEPplus   Source File: MesosResourceManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
MockMesosResourceManagerRuntimeServices() throws Exception {
	schedulerDriver = mock(SchedulerDriver.class);

	mesosConfig = mock(MesosConfiguration.class);
	when(mesosConfig.frameworkInfo()).thenReturn(Protos.FrameworkInfo.newBuilder());
	when(mesosConfig.withFrameworkInfo(any(Protos.FrameworkInfo.Builder.class))).thenReturn(mesosConfig);
	when(mesosConfig.createDriver(any(Scheduler.class), anyBoolean())).thenReturn(schedulerDriver);

	workerStore = mock(MesosWorkerStore.class);
	when(workerStore.getFrameworkID()).thenReturn(Option.<Protos.FrameworkID>empty());

	artifactServer = mock(MesosArtifactServer.class);
}
 
Example 26
@Override
public <T> T afterImmediate(String injectionPoint, T result) {
    if (!(result instanceof Protos.TaskStatus)) {
        return result;
    }
    Protos.TaskStatus status = (Protos.TaskStatus) result;

    boolean taskMatches = taskState.map(expected -> status.getState() == expected).orElse(false);
    boolean reasonMatches = reasonCode.map(expected -> status.getReason() == expected).orElse(false);
    if (taskMatches || reasonMatches) {
        return (T) status.toBuilder().setMessage(override).build();
    }
    return result;
}
 
Example 27
Source Project: dcos-cassandra-service   Source File: CleanupTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CleanupStatus createStatus(
        Protos.TaskState state,
        Optional<String> message) {

    Protos.TaskStatus.Builder builder = getStatusBuilder();
    if (message.isPresent()) {
        builder.setMessage(message.get());
    }

    return CleanupStatus.create(builder
        .setData(CassandraData.createCleanupStatusData().getBytes())
        .setState(state)
        .build());
}
 
Example 28
Source Project: dcos-commons   Source File: FrameworkScheduler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void statusUpdate(SchedulerDriver driver, Protos.TaskStatus status) {
  try {
    LOGGER.info("Received status update for taskId={} state={} message={} protobuf={}",
        status.getTaskId().getValue(),
        status.getState().toString(),
        status.getMessage(),
        TextFormat.shortDebugString(status));
    Metrics.record(status);
    TaskStatusResponse response = mesosEventClient.taskStatus(status);
    boolean eligibleToKill = TaskKiller.update(status);
    switch (response.result) { // SUPPRESS CHECKSTYLE MissingSwitchDefaultCheck
      case UNKNOWN_TASK:
        if (eligibleToKill) {
          LOGGER.info("Received status update for unknown task, marking task to be killed: {}",
              status.getTaskId().getValue());
          TaskKiller.killTask(status.getTaskId());
        } else {
          // Special case: Mesos can send TASK_LOST+REASON_RECONCILIATION as a response to a
          // prior kill request against a task that is unknown to Mesos. When this happens, we
          // don't want to repeat the kill, because that would create a Kill -> Status -> Kill
          // -> ... loop
          LOGGER.warn(
              "Received status update for unknown task, but task should not be killed again: {}",
              status.getTaskId().getValue());
        }
        break;
      case PROCESSED:
        // No-op
        break;
    }
  } catch (Throwable e) {
    logExceptionAndExit(e);
  }
}
 
Example 29
Source Project: dcos-commons   Source File: CommonIdUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFoldered2ToTaskId() throws Exception {
    Protos.TaskID taskId = CommonIdUtils.toTaskId(TEST_FOLDERED_SERVICE_NAME2, TEST_TASK_NAME);
    Assert.assertTrue(taskId.getValue().startsWith(TEST_FOLDERED_SANITIZED_NAME + "__" + TEST_TASK_NAME + "__"));
    Assert.assertNotNull(UUID.fromString(taskId.getValue().split("__")[2]));
    Assert.assertEquals(TEST_TASK_NAME, CommonIdUtils.toTaskName(taskId));
    Assert.assertEquals(TEST_FOLDERED_SANITIZED_NAME, CommonIdUtils.toSanitizedServiceName(taskId).get());
}
 
Example 30
Source Project: flink   Source File: MesosResourceAllocation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an allocation of resources for tasks to take.
 *
 * @param resources the resources to add to the allocation.
 */
public MesosResourceAllocation(Collection<Protos.Resource> resources) {
	this.resources = new ArrayList<>(checkNotNull(resources));

	// sort the resources to prefer reserved resources
	this.resources.sort(Comparator.comparing(r -> UNRESERVED_ROLE.equals(r.getRole())));
}