Search in sources :

Example 26 with ApplicationEvent

use of org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent in project hadoop by apache.

the class TestResourceLocalizationService method testLocalizationHeartbeat.

@Test(timeout = 10000)
// mocked generics
@SuppressWarnings("unchecked")
public void testLocalizationHeartbeat() throws Exception {
    List<Path> localDirs = new ArrayList<Path>();
    String[] sDirs = new String[1];
    // Making sure that we have only one local disk so that it will only be
    // selected for consecutive resource localization calls.  This is required
    // to test LocalCacheDirectoryManager.
    localDirs.add(lfs.makeQualified(new Path(basedir, 0 + "")));
    sDirs[0] = localDirs.get(0).toString();
    conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
    // Adding configuration to make sure there is only one file per
    // directory
    conf.set(YarnConfiguration.NM_LOCAL_CACHE_MAX_FILES_PER_DIRECTORY, "37");
    DrainDispatcher dispatcher = new DrainDispatcher();
    dispatcher.init(conf);
    dispatcher.start();
    EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
    dispatcher.register(ApplicationEventType.class, applicationBus);
    EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
    dispatcher.register(ContainerEventType.class, containerBus);
    ContainerExecutor exec = mock(ContainerExecutor.class);
    LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
    dirsHandler.init(conf);
    DeletionService delServiceReal = new DeletionService(exec);
    DeletionService delService = spy(delServiceReal);
    delService.init(new Configuration());
    delService.start();
    ResourceLocalizationService rawService = new ResourceLocalizationService(dispatcher, exec, delService, dirsHandler, nmContext);
    ResourceLocalizationService spyService = spy(rawService);
    doReturn(mockServer).when(spyService).createServer();
    doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class));
    FsPermission defaultPermission = FsPermission.getDirDefault().applyUMask(lfs.getUMask());
    FsPermission nmPermission = ResourceLocalizationService.NM_PRIVATE_PERM.applyUMask(lfs.getUMask());
    final Path userDir = new Path(sDirs[0].substring("file:".length()), ContainerLocalizer.USERCACHE);
    final Path fileDir = new Path(sDirs[0].substring("file:".length()), ContainerLocalizer.FILECACHE);
    final Path sysDir = new Path(sDirs[0].substring("file:".length()), ResourceLocalizationService.NM_PRIVATE_DIR);
    final FileStatus fs = new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0, defaultPermission, "", "", new Path(sDirs[0]));
    final FileStatus nmFs = new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0, nmPermission, "", "", sysDir);
    doAnswer(new Answer<FileStatus>() {

        @Override
        public FileStatus answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            if (args.length > 0) {
                if (args[0].equals(userDir) || args[0].equals(fileDir)) {
                    return fs;
                }
            }
            return nmFs;
        }
    }).when(spylfs).getFileStatus(isA(Path.class));
    try {
        spyService.init(conf);
        spyService.start();
        // init application
        final Application app = mock(Application.class);
        final ApplicationId appId = BuilderUtils.newApplicationId(314159265358979L, 3);
        when(app.getUser()).thenReturn("user0");
        when(app.getAppId()).thenReturn(appId);
        spyService.handle(new ApplicationLocalizationEvent(LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
        ArgumentMatcher<ApplicationEvent> matchesAppInit = new ArgumentMatcher<ApplicationEvent>() {

            @Override
            public boolean matches(Object o) {
                ApplicationEvent evt = (ApplicationEvent) o;
                return evt.getType() == ApplicationEventType.APPLICATION_INITED && appId == evt.getApplicationID();
            }
        };
        dispatcher.await();
        verify(applicationBus).handle(argThat(matchesAppInit));
        // init container rsrc, localizer
        Random r = new Random();
        long seed = r.nextLong();
        System.out.println("SEED: " + seed);
        r.setSeed(seed);
        final Container c = getMockContainer(appId, 42, "user0");
        FSDataOutputStream out = new FSDataOutputStream(new DataOutputBuffer(), null);
        doReturn(out).when(spylfs).createInternal(isA(Path.class), isA(EnumSet.class), isA(FsPermission.class), anyInt(), anyShort(), anyLong(), isA(Progressable.class), isA(ChecksumOpt.class), anyBoolean());
        final LocalResource resource1 = getPrivateMockedResource(r);
        LocalResource resource2 = null;
        do {
            resource2 = getPrivateMockedResource(r);
        } while (resource2 == null || resource2.equals(resource1));
        LocalResource resource3 = null;
        do {
            resource3 = getPrivateMockedResource(r);
        } while (resource3 == null || resource3.equals(resource1) || resource3.equals(resource2));
        // above call to make sure we don't get identical resources.
        final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
        final LocalResourceRequest req2 = new LocalResourceRequest(resource2);
        final LocalResourceRequest req3 = new LocalResourceRequest(resource3);
        Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs = new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
        List<LocalResourceRequest> privateResourceList = new ArrayList<LocalResourceRequest>();
        privateResourceList.add(req1);
        privateResourceList.add(req2);
        privateResourceList.add(req3);
        rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);
        spyService.handle(new ContainerLocalizationRequestEvent(c, rsrcs));
        // Sigh. Thread init of private localizer not accessible
        Thread.sleep(1000);
        dispatcher.await();
        String appStr = appId.toString();
        String ctnrStr = c.getContainerId().toString();
        ArgumentCaptor<LocalizerStartContext> contextCaptor = ArgumentCaptor.forClass(LocalizerStartContext.class);
        verify(exec).startLocalizer(contextCaptor.capture());
        LocalizerStartContext context = contextCaptor.getValue();
        Path localizationTokenPath = context.getNmPrivateContainerTokens();
        assertEquals("user0", context.getUser());
        assertEquals(appStr, context.getAppId());
        assertEquals(ctnrStr, context.getLocId());
        // heartbeat from localizer
        LocalResourceStatus rsrc1success = mock(LocalResourceStatus.class);
        LocalResourceStatus rsrc2pending = mock(LocalResourceStatus.class);
        LocalResourceStatus rsrc2success = mock(LocalResourceStatus.class);
        LocalResourceStatus rsrc3success = mock(LocalResourceStatus.class);
        LocalizerStatus stat = mock(LocalizerStatus.class);
        when(stat.getLocalizerId()).thenReturn(ctnrStr);
        when(rsrc1success.getResource()).thenReturn(resource1);
        when(rsrc2pending.getResource()).thenReturn(resource2);
        when(rsrc2success.getResource()).thenReturn(resource2);
        when(rsrc3success.getResource()).thenReturn(resource3);
        when(rsrc1success.getLocalSize()).thenReturn(4344L);
        when(rsrc2success.getLocalSize()).thenReturn(2342L);
        when(rsrc3success.getLocalSize()).thenReturn(5345L);
        URL locPath = getPath("/cache/private/blah");
        when(rsrc1success.getLocalPath()).thenReturn(locPath);
        when(rsrc2success.getLocalPath()).thenReturn(locPath);
        when(rsrc3success.getLocalPath()).thenReturn(locPath);
        when(rsrc1success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
        when(rsrc2pending.getStatus()).thenReturn(ResourceStatusType.FETCH_PENDING);
        when(rsrc2success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
        when(rsrc3success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
        // Four heartbeats with sending:
        // 1 - empty
        // 2 - resource1 FETCH_SUCCESS
        // 3 - resource2 FETCH_PENDING
        // 4 - resource2 FETCH_SUCCESS, resource3 FETCH_SUCCESS
        List<LocalResourceStatus> rsrcs4 = new ArrayList<LocalResourceStatus>();
        rsrcs4.add(rsrc2success);
        rsrcs4.add(rsrc3success);
        when(stat.getResources()).thenReturn(Collections.<LocalResourceStatus>emptyList()).thenReturn(Collections.singletonList(rsrc1success)).thenReturn(Collections.singletonList(rsrc2pending)).thenReturn(rsrcs4).thenReturn(Collections.<LocalResourceStatus>emptyList());
        String localPath = Path.SEPARATOR + ContainerLocalizer.USERCACHE + Path.SEPARATOR + "user0" + Path.SEPARATOR + ContainerLocalizer.FILECACHE;
        // First heartbeat
        LocalizerHeartbeatResponse response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        assertEquals(1, response.getResourceSpecs().size());
        assertEquals(req1, new LocalResourceRequest(response.getResourceSpecs().get(0).getResource()));
        URL localizedPath = response.getResourceSpecs().get(0).getDestinationDirectory();
        // Appending to local path unique number(10) generated as a part of
        // LocalResourcesTracker
        assertTrue(localizedPath.getFile().endsWith(localPath + Path.SEPARATOR + "10"));
        // Second heartbeat
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        assertEquals(1, response.getResourceSpecs().size());
        assertEquals(req2, new LocalResourceRequest(response.getResourceSpecs().get(0).getResource()));
        localizedPath = response.getResourceSpecs().get(0).getDestinationDirectory();
        // Resource's destination path should be now inside sub directory 0 as
        // LocalCacheDirectoryManager will be used and we have restricted number
        // of files per directory to 1.
        assertTrue(localizedPath.getFile().endsWith(localPath + Path.SEPARATOR + "0" + Path.SEPARATOR + "11"));
        // Third heartbeat
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        assertEquals(1, response.getResourceSpecs().size());
        assertEquals(req3, new LocalResourceRequest(response.getResourceSpecs().get(0).getResource()));
        localizedPath = response.getResourceSpecs().get(0).getDestinationDirectory();
        assertTrue(localizedPath.getFile().endsWith(localPath + Path.SEPARATOR + "1" + Path.SEPARATOR + "12"));
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        spyService.handle(new ContainerLocalizationEvent(LocalizationEventType.CONTAINER_RESOURCES_LOCALIZED, c));
        // get shutdown after receive CONTAINER_RESOURCES_LOCALIZED event
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.DIE, response.getLocalizerAction());
        dispatcher.await();
        // verify container notification
        ArgumentMatcher<ContainerEvent> matchesContainerLoc = new ArgumentMatcher<ContainerEvent>() {

            @Override
            public boolean matches(Object o) {
                ContainerEvent evt = (ContainerEvent) o;
                return evt.getType() == ContainerEventType.RESOURCE_LOCALIZED && c.getContainerId() == evt.getContainerID();
            }
        };
        // total 3 resource localzation calls. one for each resource.
        verify(containerBus, times(3)).handle(argThat(matchesContainerLoc));
        // Verify deletion of localization token.
        verify(delService).delete((String) isNull(), eq(localizationTokenPath));
    } finally {
        spyService.stop();
        dispatcher.stop();
        delService.stop();
    }
}
Also used : ContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor) DefaultContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor) FileStatus(org.apache.hadoop.fs.FileStatus) ContainerLocalizationRequestEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationRequestEvent) Configuration(org.apache.hadoop.conf.Configuration) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Container(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container) Random(java.util.Random) ArgumentMatcher(org.mockito.ArgumentMatcher) DataOutputBuffer(org.apache.hadoop.io.DataOutputBuffer) ApplicationLocalizationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ApplicationLocalizationEvent) FSDataOutputStream(org.apache.hadoop.fs.FSDataOutputStream) ContainerLocalizationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationEvent) ApplicationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent) DeletionService(org.apache.hadoop.yarn.server.nodemanager.DeletionService) LocalizerStatus(org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus) LocalDirsHandlerService(org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService) ChecksumOpt(org.apache.hadoop.fs.Options.ChecksumOpt) Progressable(org.apache.hadoop.util.Progressable) Collection(java.util.Collection) ApplicationId(org.apache.hadoop.yarn.api.records.ApplicationId) Application(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application) DrainDispatcher(org.apache.hadoop.yarn.event.DrainDispatcher) URL(org.apache.hadoop.yarn.api.records.URL) LocalResourceVisibility(org.apache.hadoop.yarn.api.records.LocalResourceVisibility) LocalizerStartContext(org.apache.hadoop.yarn.server.nodemanager.executor.LocalizerStartContext) FsPermission(org.apache.hadoop.fs.permission.FsPermission) Path(org.apache.hadoop.fs.Path) ContainerEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent) EnumSet(java.util.EnumSet) LocalResource(org.apache.hadoop.yarn.api.records.LocalResource) InvocationOnMock(org.mockito.invocation.InvocationOnMock) LocalizerHeartbeatResponse(org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse) LocalResourceStatus(org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalResourceStatus) Test(org.junit.Test)

Example 27 with ApplicationEvent

use of org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent in project hadoop by apache.

the class TestLogAggregationService method testMultipleAppsLogAggregation.

@Test
@SuppressWarnings("unchecked")
public void testMultipleAppsLogAggregation() throws Exception {
    this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath());
    this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, this.remoteRootLogDir.getAbsolutePath());
    String[] fileNames = new String[] { "stdout", "stderr", "syslog" };
    LogAggregationService logAggregationService = new LogAggregationService(dispatcher, this.context, this.delSrvc, super.dirsHandler);
    logAggregationService.init(this.conf);
    logAggregationService.start();
    ApplicationId application1 = BuilderUtils.newApplicationId(1234, 1);
    // AppLogDir should be created
    File app1LogDir = new File(localLogDir, application1.toString());
    app1LogDir.mkdir();
    logAggregationService.handle(new LogHandlerAppStartedEvent(application1, this.user, null, this.acls));
    ApplicationAttemptId appAttemptId1 = BuilderUtils.newApplicationAttemptId(application1, 1);
    ContainerId container11 = createContainer(appAttemptId1, 1, ContainerType.APPLICATION_MASTER);
    // Simulate log-file creation
    writeContainerLogs(app1LogDir, container11, fileNames);
    logAggregationService.handle(new LogHandlerContainerFinishedEvent(container11, 0));
    ApplicationId application2 = BuilderUtils.newApplicationId(1234, 2);
    ApplicationAttemptId appAttemptId2 = BuilderUtils.newApplicationAttemptId(application2, 1);
    File app2LogDir = new File(localLogDir, application2.toString());
    app2LogDir.mkdir();
    LogAggregationContext contextWithAMOnly = Records.newRecord(LogAggregationContext.class);
    contextWithAMOnly.setLogAggregationPolicyClassName(AMOnlyLogAggregationPolicy.class.getName());
    logAggregationService.handle(new LogHandlerAppStartedEvent(application2, this.user, null, this.acls, contextWithAMOnly));
    ContainerId container21 = createContainer(appAttemptId2, 1, ContainerType.APPLICATION_MASTER);
    writeContainerLogs(app2LogDir, container21, fileNames);
    logAggregationService.handle(new LogHandlerContainerFinishedEvent(container21, 0));
    ContainerId container12 = createContainer(appAttemptId1, 2, ContainerType.TASK);
    writeContainerLogs(app1LogDir, container12, fileNames);
    logAggregationService.handle(new LogHandlerContainerFinishedEvent(container12, 0));
    ApplicationId application3 = BuilderUtils.newApplicationId(1234, 3);
    ApplicationAttemptId appAttemptId3 = BuilderUtils.newApplicationAttemptId(application3, 1);
    File app3LogDir = new File(localLogDir, application3.toString());
    app3LogDir.mkdir();
    LogAggregationContext contextWithAMAndFailed = Records.newRecord(LogAggregationContext.class);
    contextWithAMAndFailed.setLogAggregationPolicyClassName(AMOrFailedContainerLogAggregationPolicy.class.getName());
    logAggregationService.handle(new LogHandlerAppStartedEvent(application3, this.user, null, this.acls, contextWithAMAndFailed));
    dispatcher.await();
    ApplicationEvent[] expectedInitEvents = new ApplicationEvent[] { new ApplicationEvent(application1, ApplicationEventType.APPLICATION_LOG_HANDLING_INITED), new ApplicationEvent(application2, ApplicationEventType.APPLICATION_LOG_HANDLING_INITED), new ApplicationEvent(application3, ApplicationEventType.APPLICATION_LOG_HANDLING_INITED) };
    checkEvents(appEventHandler, expectedInitEvents, false, "getType", "getApplicationID");
    reset(appEventHandler);
    ContainerId container31 = createContainer(appAttemptId3, 1, ContainerType.APPLICATION_MASTER);
    writeContainerLogs(app3LogDir, container31, fileNames);
    logAggregationService.handle(new LogHandlerContainerFinishedEvent(container31, 0));
    ContainerId container32 = createContainer(appAttemptId3, 2, ContainerType.TASK);
    writeContainerLogs(app3LogDir, container32, fileNames);
    logAggregationService.handle(// Failed 
    new LogHandlerContainerFinishedEvent(container32, 1));
    ContainerId container22 = createContainer(appAttemptId2, 2, ContainerType.TASK);
    writeContainerLogs(app2LogDir, container22, fileNames);
    logAggregationService.handle(new LogHandlerContainerFinishedEvent(container22, 0));
    ContainerId container33 = createContainer(appAttemptId3, 3, ContainerType.TASK);
    writeContainerLogs(app3LogDir, container33, fileNames);
    logAggregationService.handle(new LogHandlerContainerFinishedEvent(container33, 0));
    logAggregationService.handle(new LogHandlerAppFinishedEvent(application2));
    logAggregationService.handle(new LogHandlerAppFinishedEvent(application3));
    logAggregationService.handle(new LogHandlerAppFinishedEvent(application1));
    logAggregationService.stop();
    assertEquals(0, logAggregationService.getNumAggregators());
    verifyContainerLogs(logAggregationService, application1, new ContainerId[] { container11, container12 }, fileNames, 3, false);
    verifyContainerLogs(logAggregationService, application2, new ContainerId[] { container21 }, fileNames, 3, false);
    verifyContainerLogs(logAggregationService, application3, new ContainerId[] { container31, container32 }, fileNames, 3, false);
    dispatcher.await();
    ApplicationEvent[] expectedFinishedEvents = new ApplicationEvent[] { new ApplicationEvent(application1, ApplicationEventType.APPLICATION_LOG_HANDLING_FINISHED), new ApplicationEvent(application2, ApplicationEventType.APPLICATION_LOG_HANDLING_FINISHED), new ApplicationEvent(application3, ApplicationEventType.APPLICATION_LOG_HANDLING_FINISHED) };
    checkEvents(appEventHandler, expectedFinishedEvents, false, "getType", "getApplicationID");
}
Also used : ApplicationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent) LogHandlerContainerFinishedEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerContainerFinishedEvent) ApplicationAttemptId(org.apache.hadoop.yarn.api.records.ApplicationAttemptId) LogHandlerAppStartedEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppStartedEvent) ContainerId(org.apache.hadoop.yarn.api.records.ContainerId) LogHandlerAppFinishedEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppFinishedEvent) ApplicationId(org.apache.hadoop.yarn.api.records.ApplicationId) File(java.io.File) LogAggregationContext(org.apache.hadoop.yarn.api.records.LogAggregationContext) BaseContainerManagerTest(org.apache.hadoop.yarn.server.nodemanager.containermanager.BaseContainerManagerTest) Test(org.junit.Test)

Example 28 with ApplicationEvent

use of org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent in project hadoop by apache.

the class TestResourceLocalizationService method testResourceRelease.

@Test
// mocked generics
@SuppressWarnings("unchecked")
public void testResourceRelease() throws Exception {
    List<Path> localDirs = new ArrayList<Path>();
    String[] sDirs = new String[4];
    for (int i = 0; i < 4; ++i) {
        localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
        sDirs[i] = localDirs.get(i).toString();
    }
    conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
    LocalizerTracker mockLocallilzerTracker = mock(LocalizerTracker.class);
    DrainDispatcher dispatcher = new DrainDispatcher();
    dispatcher.init(conf);
    dispatcher.start();
    EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
    dispatcher.register(ApplicationEventType.class, applicationBus);
    EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
    dispatcher.register(ContainerEventType.class, containerBus);
    //Ignore actual localization
    EventHandler<LocalizerEvent> localizerBus = mock(EventHandler.class);
    dispatcher.register(LocalizerEventType.class, localizerBus);
    ContainerExecutor exec = mock(ContainerExecutor.class);
    LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
    dirsHandler.init(conf);
    DeletionService delService = new DeletionService(exec);
    delService.init(new Configuration());
    delService.start();
    ResourceLocalizationService rawService = new ResourceLocalizationService(dispatcher, exec, delService, dirsHandler, nmContext);
    ResourceLocalizationService spyService = spy(rawService);
    doReturn(mockServer).when(spyService).createServer();
    doReturn(mockLocallilzerTracker).when(spyService).createLocalizerTracker(isA(Configuration.class));
    doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class));
    try {
        spyService.init(conf);
        spyService.start();
        final String user = "user0";
        // init application
        final Application app = mock(Application.class);
        final ApplicationId appId = BuilderUtils.newApplicationId(314159265358979L, 3);
        when(app.getUser()).thenReturn(user);
        when(app.getAppId()).thenReturn(appId);
        spyService.handle(new ApplicationLocalizationEvent(LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
        dispatcher.await();
        //Get a handle on the trackers after they're setup with INIT_APP_RESOURCES
        LocalResourcesTracker appTracker = spyService.getLocalResourcesTracker(LocalResourceVisibility.APPLICATION, user, appId);
        LocalResourcesTracker privTracker = spyService.getLocalResourcesTracker(LocalResourceVisibility.PRIVATE, user, appId);
        LocalResourcesTracker pubTracker = spyService.getLocalResourcesTracker(LocalResourceVisibility.PUBLIC, user, appId);
        // init container.
        final Container c = getMockContainer(appId, 42, user);
        // init resources
        Random r = new Random();
        long seed = r.nextLong();
        System.out.println("SEED: " + seed);
        r.setSeed(seed);
        // Send localization requests for one resource of each type.
        final LocalResource privResource = getPrivateMockedResource(r);
        final LocalResourceRequest privReq = new LocalResourceRequest(privResource);
        final LocalResource pubResource = getPublicMockedResource(r);
        final LocalResourceRequest pubReq = new LocalResourceRequest(pubResource);
        final LocalResource pubResource2 = getPublicMockedResource(r);
        final LocalResourceRequest pubReq2 = new LocalResourceRequest(pubResource2);
        final LocalResource appResource = getAppMockedResource(r);
        final LocalResourceRequest appReq = new LocalResourceRequest(appResource);
        Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req = new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
        req.put(LocalResourceVisibility.PRIVATE, Collections.singletonList(privReq));
        req.put(LocalResourceVisibility.PUBLIC, Collections.singletonList(pubReq));
        req.put(LocalResourceVisibility.APPLICATION, Collections.singletonList(appReq));
        Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req2 = new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
        req2.put(LocalResourceVisibility.PRIVATE, Collections.singletonList(privReq));
        req2.put(LocalResourceVisibility.PUBLIC, Collections.singletonList(pubReq2));
        Set<LocalResourceRequest> pubRsrcs = new HashSet<LocalResourceRequest>();
        pubRsrcs.add(pubReq);
        pubRsrcs.add(pubReq2);
        // Send Request event
        spyService.handle(new ContainerLocalizationRequestEvent(c, req));
        spyService.handle(new ContainerLocalizationRequestEvent(c, req2));
        dispatcher.await();
        int privRsrcCount = 0;
        for (LocalizedResource lr : privTracker) {
            privRsrcCount++;
            Assert.assertEquals("Incorrect reference count", 2, lr.getRefCount());
            Assert.assertEquals(privReq, lr.getRequest());
        }
        Assert.assertEquals(1, privRsrcCount);
        int pubRsrcCount = 0;
        for (LocalizedResource lr : pubTracker) {
            pubRsrcCount++;
            Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
            pubRsrcs.remove(lr.getRequest());
        }
        Assert.assertEquals(0, pubRsrcs.size());
        Assert.assertEquals(2, pubRsrcCount);
        int appRsrcCount = 0;
        for (LocalizedResource lr : appTracker) {
            appRsrcCount++;
            Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
            Assert.assertEquals(appReq, lr.getRequest());
        }
        Assert.assertEquals(1, appRsrcCount);
        //Send Cleanup Event
        spyService.handle(new ContainerLocalizationCleanupEvent(c, req));
        verify(mockLocallilzerTracker).cleanupPrivLocalizers("container_314159265358979_0003_01_000042");
        req2.remove(LocalResourceVisibility.PRIVATE);
        spyService.handle(new ContainerLocalizationCleanupEvent(c, req2));
        dispatcher.await();
        pubRsrcs.add(pubReq);
        pubRsrcs.add(pubReq2);
        privRsrcCount = 0;
        for (LocalizedResource lr : privTracker) {
            privRsrcCount++;
            Assert.assertEquals("Incorrect reference count", 1, lr.getRefCount());
            Assert.assertEquals(privReq, lr.getRequest());
        }
        Assert.assertEquals(1, privRsrcCount);
        pubRsrcCount = 0;
        for (LocalizedResource lr : pubTracker) {
            pubRsrcCount++;
            Assert.assertEquals("Incorrect reference count", 0, lr.getRefCount());
            pubRsrcs.remove(lr.getRequest());
        }
        Assert.assertEquals(0, pubRsrcs.size());
        Assert.assertEquals(2, pubRsrcCount);
        appRsrcCount = 0;
        for (LocalizedResource lr : appTracker) {
            appRsrcCount++;
        }
        Assert.assertEquals(0, appRsrcCount);
    } finally {
        dispatcher.stop();
        delService.stop();
    }
}
Also used : DrainDispatcher(org.apache.hadoop.yarn.event.DrainDispatcher) ContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor) DefaultContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor) ContainerLocalizationRequestEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationRequestEvent) Configuration(org.apache.hadoop.conf.Configuration) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LocalResourceVisibility(org.apache.hadoop.yarn.api.records.LocalResourceVisibility) Container(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container) Random(java.util.Random) ApplicationLocalizationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ApplicationLocalizationEvent) HashSet(java.util.HashSet) Path(org.apache.hadoop.fs.Path) ContainerEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent) ApplicationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent) DeletionService(org.apache.hadoop.yarn.server.nodemanager.DeletionService) ContainerLocalizationCleanupEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationCleanupEvent) LocalDirsHandlerService(org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService) LocalResource(org.apache.hadoop.yarn.api.records.LocalResource) LocalizerEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerEvent) LocalizerTracker(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ResourceLocalizationService.LocalizerTracker) Collection(java.util.Collection) ApplicationId(org.apache.hadoop.yarn.api.records.ApplicationId) Application(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application) Test(org.junit.Test)

Example 29 with ApplicationEvent

use of org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent in project hadoop by apache.

the class TestResourceLocalizationService method testParallelDownloadAttemptsForPrivateResource.

@Test(timeout = 100000)
@SuppressWarnings("unchecked")
public void testParallelDownloadAttemptsForPrivateResource() throws Exception {
    DrainDispatcher dispatcher1 = null;
    try {
        dispatcher1 = new DrainDispatcher();
        String user = "testuser";
        ApplicationId appId = BuilderUtils.newApplicationId(1, 1);
        // creating one local directory
        List<Path> localDirs = new ArrayList<Path>();
        String[] sDirs = new String[1];
        for (int i = 0; i < 1; ++i) {
            localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
            sDirs[i] = localDirs.get(i).toString();
        }
        conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
        LocalDirsHandlerService localDirHandler = new LocalDirsHandlerService();
        localDirHandler.init(conf);
        // Registering event handlers
        EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
        dispatcher1.register(ApplicationEventType.class, applicationBus);
        EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
        dispatcher1.register(ContainerEventType.class, containerBus);
        ContainerExecutor exec = mock(ContainerExecutor.class);
        DeletionService delService = mock(DeletionService.class);
        LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
        // initializing directory handler.
        dirsHandler.init(conf);
        dispatcher1.init(conf);
        dispatcher1.start();
        ResourceLocalizationService rls = new ResourceLocalizationService(dispatcher1, exec, delService, localDirHandler, nmContext);
        dispatcher1.register(LocalizationEventType.class, rls);
        rls.init(conf);
        rls.handle(createApplicationLocalizationEvent(user, appId));
        LocalResourceRequest req = new LocalResourceRequest(new Path("file:///tmp"), 123L, LocalResourceType.FILE, LocalResourceVisibility.PRIVATE, "");
        // We need to pre-populate the LocalizerRunner as the
        // Resource Localization Service code internally starts them which
        // definitely we don't want.
        // creating new containers and populating corresponding localizer runners
        // Container - 1
        Container container1 = createMockContainer(user, 1);
        String localizerId1 = container1.getContainerId().toString();
        rls.getPrivateLocalizers().put(localizerId1, rls.new LocalizerRunner(new LocalizerContext(user, container1.getContainerId(), null), localizerId1));
        LocalizerRunner localizerRunner1 = rls.getLocalizerRunner(localizerId1);
        dispatcher1.getEventHandler().handle(createContainerLocalizationEvent(container1, LocalResourceVisibility.PRIVATE, req));
        Assert.assertTrue(waitForPrivateDownloadToStart(rls, localizerId1, 1, 5000));
        // Container - 2 now makes the request.
        ContainerImpl container2 = createMockContainer(user, 2);
        String localizerId2 = container2.getContainerId().toString();
        rls.getPrivateLocalizers().put(localizerId2, rls.new LocalizerRunner(new LocalizerContext(user, container2.getContainerId(), null), localizerId2));
        LocalizerRunner localizerRunner2 = rls.getLocalizerRunner(localizerId2);
        dispatcher1.getEventHandler().handle(createContainerLocalizationEvent(container2, LocalResourceVisibility.PRIVATE, req));
        Assert.assertTrue(waitForPrivateDownloadToStart(rls, localizerId2, 1, 5000));
        // Retrieving localized resource.
        LocalResourcesTracker tracker = rls.getLocalResourcesTracker(LocalResourceVisibility.PRIVATE, user, appId);
        LocalizedResource lr = tracker.getLocalizedResource(req);
        // Resource would now have moved into DOWNLOADING state
        Assert.assertEquals(ResourceState.DOWNLOADING, lr.getState());
        // Resource should have one permit
        Assert.assertEquals(1, lr.sem.availablePermits());
        // Resource Localization Service receives first heart beat from
        // ContainerLocalizer for container1
        LocalizerHeartbeatResponse response1 = rls.heartbeat(createLocalizerStatus(localizerId1));
        // Resource must have been added to scheduled map
        Assert.assertEquals(1, localizerRunner1.scheduled.size());
        // Checking resource in the response and also available permits for it.
        Assert.assertEquals(req.getResource(), response1.getResourceSpecs().get(0).getResource().getResource());
        Assert.assertEquals(0, lr.sem.availablePermits());
        // Resource Localization Service now receives first heart beat from
        // ContainerLocalizer for container2
        LocalizerHeartbeatResponse response2 = rls.heartbeat(createLocalizerStatus(localizerId2));
        // Resource must not have been added to scheduled map
        Assert.assertEquals(0, localizerRunner2.scheduled.size());
        // No resource is returned in response
        Assert.assertEquals(0, response2.getResourceSpecs().size());
        // ContainerLocalizer - 1 now sends failed resource heartbeat.
        rls.heartbeat(createLocalizerStatusForFailedResource(localizerId1, req));
        // Resource Localization should fail and state is modified accordingly.
        // Also Local should be release on the LocalizedResource.
        Assert.assertTrue(waitForResourceState(lr, rls, req, LocalResourceVisibility.PRIVATE, user, appId, ResourceState.FAILED, 5000));
        Assert.assertTrue(lr.getState().equals(ResourceState.FAILED));
        Assert.assertEquals(0, localizerRunner1.scheduled.size());
        // Now Container-2 once again sends heart beat to resource localization
        // service
        // Now container-2 again try to download the resource it should still
        // not get the resource as the resource is now not in DOWNLOADING state.
        response2 = rls.heartbeat(createLocalizerStatus(localizerId2));
        // Resource must not have been added to scheduled map.
        // Also as the resource has failed download it will be removed from
        // pending list.
        Assert.assertEquals(0, localizerRunner2.scheduled.size());
        Assert.assertEquals(0, localizerRunner2.pending.size());
        Assert.assertEquals(0, response2.getResourceSpecs().size());
    } finally {
        if (dispatcher1 != null) {
            dispatcher1.stop();
        }
    }
}
Also used : DrainDispatcher(org.apache.hadoop.yarn.event.DrainDispatcher) Path(org.apache.hadoop.fs.Path) ContainerEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent) ContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor) DefaultContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor) ArrayList(java.util.ArrayList) ApplicationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent) DeletionService(org.apache.hadoop.yarn.server.nodemanager.DeletionService) LocalDirsHandlerService(org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService) Container(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container) LocalizerRunner(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ResourceLocalizationService.LocalizerRunner) ContainerImpl(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl) LocalizerHeartbeatResponse(org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse) ApplicationId(org.apache.hadoop.yarn.api.records.ApplicationId) Test(org.junit.Test)

Example 30 with ApplicationEvent

use of org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent in project hadoop by apache.

the class TestLogAggregationService method testFailedDirsLocalFileDeletionAfterUpload.

/*
   * Test to make sure we handle cases where the directories we get back from
   * the LocalDirsHandler may have issues including the log dir not being
   * present as well as other issues. The test uses helper functions from
   * TestNonAggregatingLogHandler.
   */
@Test
public void testFailedDirsLocalFileDeletionAfterUpload() throws Exception {
    // setup conf and services
    DeletionService mockDelService = mock(DeletionService.class);
    File[] localLogDirs = TestNonAggregatingLogHandler.getLocalLogDirFiles(this.getClass().getName(), 7);
    final List<String> localLogDirPaths = new ArrayList<String>(localLogDirs.length);
    for (int i = 0; i < localLogDirs.length; i++) {
        localLogDirPaths.add(localLogDirs[i].getAbsolutePath());
    }
    String localLogDirsString = StringUtils.join(localLogDirPaths, ",");
    this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDirsString);
    this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, this.remoteRootLogDir.getAbsolutePath());
    this.conf.setLong(YarnConfiguration.NM_DISK_HEALTH_CHECK_INTERVAL_MS, 500);
    ApplicationId application1 = BuilderUtils.newApplicationId(1234, 1);
    ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId(application1, 1);
    this.dirsHandler = new LocalDirsHandlerService();
    LocalDirsHandlerService mockDirsHandler = mock(LocalDirsHandlerService.class);
    LogAggregationService logAggregationService = spy(new LogAggregationService(dispatcher, this.context, mockDelService, mockDirsHandler));
    AbstractFileSystem spylfs = spy(FileContext.getLocalFSFileContext().getDefaultFileSystem());
    FileContext lfs = FileContext.getFileContext(spylfs, conf);
    doReturn(lfs).when(logAggregationService).getLocalFileContext(isA(Configuration.class));
    logAggregationService.init(this.conf);
    logAggregationService.start();
    TestNonAggregatingLogHandler.runMockedFailedDirs(logAggregationService, application1, user, mockDelService, mockDirsHandler, conf, spylfs, lfs, localLogDirs);
    logAggregationService.stop();
    assertEquals(0, logAggregationService.getNumAggregators());
    verify(logAggregationService).closeFileSystems(any(UserGroupInformation.class));
    ApplicationEvent[] expectedEvents = new ApplicationEvent[] { new ApplicationEvent(appAttemptId.getApplicationId(), ApplicationEventType.APPLICATION_LOG_HANDLING_INITED), new ApplicationEvent(appAttemptId.getApplicationId(), ApplicationEventType.APPLICATION_LOG_HANDLING_FINISHED) };
    checkEvents(appEventHandler, expectedEvents, true, "getType", "getApplicationID");
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) DeletionService(org.apache.hadoop.yarn.server.nodemanager.DeletionService) ArrayList(java.util.ArrayList) ApplicationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent) ApplicationAttemptId(org.apache.hadoop.yarn.api.records.ApplicationAttemptId) LocalDirsHandlerService(org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService) AbstractFileSystem(org.apache.hadoop.fs.AbstractFileSystem) ApplicationId(org.apache.hadoop.yarn.api.records.ApplicationId) File(java.io.File) FileContext(org.apache.hadoop.fs.FileContext) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) BaseContainerManagerTest(org.apache.hadoop.yarn.server.nodemanager.containermanager.BaseContainerManagerTest) Test(org.junit.Test)

Aggregations

ApplicationEvent (org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent)30 ApplicationId (org.apache.hadoop.yarn.api.records.ApplicationId)24 Test (org.junit.Test)21 ArrayList (java.util.ArrayList)15 Path (org.apache.hadoop.fs.Path)15 DeletionService (org.apache.hadoop.yarn.server.nodemanager.DeletionService)13 LocalDirsHandlerService (org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService)13 Application (org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application)13 Container (org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container)13 ContainerEvent (org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent)13 DrainDispatcher (org.apache.hadoop.yarn.event.DrainDispatcher)12 HashMap (java.util.HashMap)11 LocalResource (org.apache.hadoop.yarn.api.records.LocalResource)11 ApplicationLocalizationEvent (org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ApplicationLocalizationEvent)11 ContainerLocalizationRequestEvent (org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationRequestEvent)11 IOException (java.io.IOException)10 Collection (java.util.Collection)10 Configuration (org.apache.hadoop.conf.Configuration)10 LocalResourceVisibility (org.apache.hadoop.yarn.api.records.LocalResourceVisibility)10 YarnConfiguration (org.apache.hadoop.yarn.conf.YarnConfiguration)10