Search in sources :

Example 16 with ProcessorLocality

use of org.apache.samza.job.model.ProcessorLocality in project samza by apache.

the class TestContainerProcessManager method testContainerRequestedRetriesNotExceedingWindowOnFailureWithUnknownCode.

private void testContainerRequestedRetriesNotExceedingWindowOnFailureWithUnknownCode(boolean withHostAffinity, boolean failAfterRetries) throws Exception {
    int maxRetries = 3;
    String processorId = "0";
    ClusterManagerConfig clusterManagerConfig = new ClusterManagerConfig(getConfigWithHostAffinityAndRetries(withHostAffinity, maxRetries, failAfterRetries));
    SamzaApplicationState state = new SamzaApplicationState(getJobModelManager(1));
    MockClusterResourceManagerCallback callback = new MockClusterResourceManagerCallback();
    MockClusterResourceManager clusterResourceManager = new MockClusterResourceManager(callback, state);
    FaultDomainManager faultDomainManager = mock(FaultDomainManager.class);
    LocalityManager mockLocalityManager = mock(LocalityManager.class);
    if (withHostAffinity) {
        when(mockLocalityManager.readLocality()).thenReturn(new LocalityModel(ImmutableMap.of("0", new ProcessorLocality("0", "host1"))));
    } else {
        when(mockLocalityManager.readLocality()).thenReturn(new LocalityModel(new HashMap<>()));
    }
    ContainerManager containerManager = buildContainerManager(containerPlacementMetadataStore, state, clusterResourceManager, clusterManagerConfig.getHostAffinityEnabled(), false, mockLocalityManager, faultDomainManager);
    MockContainerAllocatorWithoutHostAffinity allocator = new MockContainerAllocatorWithoutHostAffinity(clusterResourceManager, clusterManagerConfig, state, containerManager);
    ContainerProcessManager cpm = buildContainerProcessManager(clusterManagerConfig, state, clusterResourceManager, Optional.of(allocator), mockLocalityManager, false, faultDomainManager);
    // start triggers a request
    cpm.start();
    assertFalse(cpm.shouldShutdown());
    assertEquals(1, allocator.getContainerRequestState().numPendingRequests());
    assertEquals(0, allocator.getContainerRequestState().numDelayedRequests());
    SamzaResource container = new SamzaResource(1, 1024, "host1", "id0");
    cpm.onResourceAllocated(container);
    // Allow container to run and update state
    if (!allocator.awaitContainersStart(1, 2, TimeUnit.SECONDS)) {
        fail("timed out waiting for the containers to start");
    }
    cpm.onStreamProcessorLaunchSuccess(container);
    // Mock 2nd failure not exceeding retry window.
    cpm.getProcessorFailures().put(processorId, new ProcessorFailure(1, Instant.now(), Duration.ZERO));
    cpm.onResourceCompleted(new SamzaResourceStatus(container.getContainerId(), "diagnostics", 1));
    assertEquals(false, cpm.getJobFailureCriteriaMet());
    assertEquals(2, cpm.getProcessorFailures().get(processorId).getCount());
    assertFalse(cpm.shouldShutdown());
    assertEquals(1, allocator.getContainerRequestState().numPendingRequests());
    assertEquals(0, allocator.getContainerRequestState().numDelayedRequests());
    cpm.onResourceAllocated(container);
    // Allow container to run and update state
    if (!allocator.awaitContainersStart(1, 2, TimeUnit.SECONDS)) {
        fail("timed out waiting for the containers to start");
    }
    cpm.onStreamProcessorLaunchSuccess(container);
    // Mock 3rd failure not exceeding retry window.
    cpm.getProcessorFailures().put(processorId, new ProcessorFailure(2, Instant.now(), Duration.ZERO));
    cpm.onResourceCompleted(new SamzaResourceStatus(container.getContainerId(), "diagnostics", 1));
    assertEquals(false, cpm.getJobFailureCriteriaMet());
    assertEquals(3, cpm.getProcessorFailures().get(processorId).getCount());
    assertFalse(cpm.shouldShutdown());
    if (withHostAffinity) {
        assertEquals(0, allocator.getContainerRequestState().numPendingRequests());
        assertEquals(1, allocator.getContainerRequestState().numDelayedRequests());
    } else {
        assertEquals(1, allocator.getContainerRequestState().numPendingRequests());
        assertEquals(0, allocator.getContainerRequestState().numDelayedRequests());
    }
    cpm.onResourceAllocated(container);
    if (withHostAffinity) {
        if (allocator.awaitContainersStart(1, 2, TimeUnit.SECONDS)) {
            // No delayed retry requests for there host affinity is disabled. Call back should return immediately.
            fail("Expecting a delayed request so allocator callback should have timed out waiting for a response.");
        }
        // For the sake of testing the mocked 4th failure below, send delayed requests now.
        SamzaResourceRequest request = allocator.getContainerRequestState().getDelayedRequestsQueue().poll();
        SamzaResourceRequest fastForwardRequest = new SamzaResourceRequest(request.getNumCores(), request.getMemoryMB(), request.getPreferredHost(), request.getProcessorId(), Instant.now().minusSeconds(1));
        allocator.getContainerRequestState().getDelayedRequestsQueue().add(fastForwardRequest);
        int numSent = allocator.getContainerRequestState().sendPendingDelayedResourceRequests();
        assertEquals(1, numSent);
        cpm.onResourceAllocated(container);
    }
    if (!allocator.awaitContainersStart(1, 2, TimeUnit.SECONDS)) {
        // No delayed retry requests for there host affinity is disabled. Call back should return immediately.
        fail("Timed out waiting for the containers to start");
    }
    cpm.onStreamProcessorLaunchSuccess(container);
    // Mock 4th failure not exceeding retry window.
    cpm.getProcessorFailures().put(processorId, new ProcessorFailure(3, Instant.now(), Duration.ZERO));
    cpm.onResourceCompleted(new SamzaResourceStatus(container.getContainerId(), "diagnostics", 1));
    // expecting failed container
    assertEquals(failAfterRetries, cpm.getJobFailureCriteriaMet());
    // count won't update on failure
    assertEquals(3, cpm.getProcessorFailures().get(processorId).getCount());
    if (failAfterRetries) {
        assertTrue(cpm.shouldShutdown());
    } else {
        assertFalse(cpm.shouldShutdown());
    }
    assertEquals(0, allocator.getContainerRequestState().numPendingRequests());
    assertEquals(0, allocator.getContainerRequestState().numDelayedRequests());
    cpm.stop();
}
Also used : HashMap(java.util.HashMap) Matchers.anyString(org.mockito.Matchers.anyString) LocalityModel(org.apache.samza.job.model.LocalityModel) ProcessorLocality(org.apache.samza.job.model.ProcessorLocality) ClusterManagerConfig(org.apache.samza.config.ClusterManagerConfig) LocalityManager(org.apache.samza.container.LocalityManager)

Example 17 with ProcessorLocality

use of org.apache.samza.job.model.ProcessorLocality in project samza by apache.

the class ContainerProcessManager method start.

public void start() {
    LOG.info("Starting the container process manager");
    int containerRetryCount = clusterManagerConfig.getContainerRetryCount();
    if (containerRetryCount > -1) {
        LOG.info("Max retries on restarting failed containers: {}", containerRetryCount);
    } else {
        LOG.info("Infinite retries on restarting failed containers");
    }
    if (jvmMetrics != null) {
        jvmMetrics.start();
    }
    if (metricsReporters != null) {
        metricsReporters.values().forEach(reporter -> reporter.start());
    }
    if (diagnosticsManager.isPresent()) {
        diagnosticsManager.get().start();
    }
    // In AM-HA, clusterResourceManager receives already running containers
    // and invokes onStreamProcessorLaunchSuccess which inturn updates state
    // hence state has to be set prior to starting clusterResourceManager.
    state.processorCount.set(state.jobModelManager.jobModel().getContainers().size());
    state.neededProcessors.set(state.jobModelManager.jobModel().getContainers().size());
    LOG.info("Starting the cluster resource manager");
    clusterResourceManager.start();
    // Request initial set of containers
    LocalityModel localityModel = localityManager.readLocality();
    Map<String, String> processorToHost = new HashMap<>();
    state.jobModelManager.jobModel().getContainers().keySet().forEach((processorId) -> {
        String host = Optional.ofNullable(localityModel.getProcessorLocality(processorId)).map(ProcessorLocality::host).filter(StringUtils::isNotBlank).orElse(null);
        processorToHost.put(processorId, host);
    });
    if (jobConfig.getApplicationMasterHighAvailabilityEnabled()) {
        // don't request resource for container that is already running
        state.runningProcessors.forEach((processorId, samzaResource) -> {
            LOG.info("Not requesting container for processorId: {} since its already running as containerId: {}", processorId, samzaResource.getContainerId());
            processorToHost.remove(processorId);
            if (restartContainers) {
                clusterResourceManager.stopStreamProcessor(samzaResource);
            }
        });
    }
    containerAllocator.requestResources(processorToHost);
    // Start container allocator thread
    LOG.info("Starting the container allocator thread");
    allocatorThread.start();
    LOG.info("Starting the container process manager");
}
Also used : ProcessorLocality(org.apache.samza.job.model.ProcessorLocality) HashMap(java.util.HashMap) LocalityModel(org.apache.samza.job.model.LocalityModel)

Example 18 with ProcessorLocality

use of org.apache.samza.job.model.ProcessorLocality in project samza by apache.

the class SamzaTaskProxy method readTasksFromCoordinatorStream.

/**
 * Builds list of {@link Task} from job model in coordinator stream.
 * @param consumer system consumer associated with a job's coordinator stream.
 * @return list of {@link Task} constructed from job model in coordinator stream.
 */
protected List<Task> readTasksFromCoordinatorStream(CoordinatorStreamSystemConsumer consumer) {
    CoordinatorStreamStore coordinatorStreamStore = new CoordinatorStreamStore(consumer.getConfig(), new MetricsRegistryMap());
    LocalityManager localityManager = new LocalityManager(coordinatorStreamStore);
    Map<String, ProcessorLocality> containerLocalities = localityManager.readLocality().getProcessorLocalities();
    TaskAssignmentManager taskAssignmentManager = new TaskAssignmentManager(new NamespaceAwareCoordinatorStreamStore(coordinatorStreamStore, SetTaskContainerMapping.TYPE), new NamespaceAwareCoordinatorStreamStore(coordinatorStreamStore, SetTaskModeMapping.TYPE));
    Map<String, String> taskNameToContainerIdMapping = taskAssignmentManager.readTaskAssignment();
    StorageConfig storageConfig = new StorageConfig(consumer.getConfig());
    List<String> storeNames = storageConfig.getStoreNames();
    return taskNameToContainerIdMapping.entrySet().stream().map(entry -> {
        String hostName = Optional.ofNullable(containerLocalities.get(entry.getValue())).map(ProcessorLocality::host).orElse(null);
        return new Task(hostName, entry.getKey(), entry.getValue(), new ArrayList<>(), storeNames);
    }).collect(Collectors.toList());
}
Also used : CoordinatorStreamStore(org.apache.samza.coordinator.metadatastore.CoordinatorStreamStore) SetTaskModeMapping(org.apache.samza.coordinator.stream.messages.SetTaskModeMapping) Task(org.apache.samza.rest.model.Task) LoggerFactory(org.slf4j.LoggerFactory) JobConfig(org.apache.samza.config.JobConfig) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) TaskAssignmentManager(org.apache.samza.container.grouper.task.TaskAssignmentManager) JobInstance(org.apache.samza.rest.proxy.job.JobInstance) URI(java.net.URI) MapConfig(org.apache.samza.config.MapConfig) NamespaceAwareCoordinatorStreamStore(org.apache.samza.coordinator.metadatastore.NamespaceAwareCoordinatorStreamStore) StorageConfig(org.apache.samza.config.StorageConfig) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) InstallationFinder(org.apache.samza.rest.proxy.installation.InstallationFinder) ConfigFactory(org.apache.samza.config.ConfigFactory) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) SamzaException(org.apache.samza.SamzaException) LocalityManager(org.apache.samza.container.LocalityManager) CoordinatorStreamSystemConsumer(org.apache.samza.coordinator.stream.CoordinatorStreamSystemConsumer) List(java.util.List) ReflectionUtil(org.apache.samza.util.ReflectionUtil) ProcessorLocality(org.apache.samza.job.model.ProcessorLocality) Optional(java.util.Optional) InstallationRecord(org.apache.samza.rest.proxy.installation.InstallationRecord) Preconditions(com.google.common.base.Preconditions) Config(org.apache.samza.config.Config) SetTaskContainerMapping(org.apache.samza.coordinator.stream.messages.SetTaskContainerMapping) CoordinatorStreamUtil(org.apache.samza.util.CoordinatorStreamUtil) MetricsRegistryMap(org.apache.samza.metrics.MetricsRegistryMap) Task(org.apache.samza.rest.model.Task) StorageConfig(org.apache.samza.config.StorageConfig) ArrayList(java.util.ArrayList) ProcessorLocality(org.apache.samza.job.model.ProcessorLocality) NamespaceAwareCoordinatorStreamStore(org.apache.samza.coordinator.metadatastore.NamespaceAwareCoordinatorStreamStore) CoordinatorStreamStore(org.apache.samza.coordinator.metadatastore.CoordinatorStreamStore) NamespaceAwareCoordinatorStreamStore(org.apache.samza.coordinator.metadatastore.NamespaceAwareCoordinatorStreamStore) TaskAssignmentManager(org.apache.samza.container.grouper.task.TaskAssignmentManager) MetricsRegistryMap(org.apache.samza.metrics.MetricsRegistryMap) LocalityManager(org.apache.samza.container.LocalityManager)

Aggregations

ProcessorLocality (org.apache.samza.job.model.ProcessorLocality)18 LocalityModel (org.apache.samza.job.model.LocalityModel)12 LocalityManager (org.apache.samza.container.LocalityManager)10 HashMap (java.util.HashMap)8 ClusterManagerConfig (org.apache.samza.config.ClusterManagerConfig)6 MetricsRegistryMap (org.apache.samza.metrics.MetricsRegistryMap)6 MapConfig (org.apache.samza.config.MapConfig)5 Test (org.junit.Test)5 JobConfig (org.apache.samza.config.JobConfig)4 LocationId (org.apache.samza.runtime.LocationId)4 Matchers.anyString (org.mockito.Matchers.anyString)4 Map (java.util.Map)3 Config (org.apache.samza.config.Config)3 CoordinatorStreamStore (org.apache.samza.coordinator.metadatastore.CoordinatorStreamStore)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2 StringUtils (org.apache.commons.lang3.StringUtils)2 ContainerPlacementMetadataStore (org.apache.samza.clustermanager.container.placement.ContainerPlacementMetadataStore)2