Example usage for org.apache.hadoop.yarn.api.records ApplicationReport getApplicationId

List of usage examples for org.apache.hadoop.yarn.api.records ApplicationReport getApplicationId

Introduction

In this page you can find the example usage for org.apache.hadoop.yarn.api.records ApplicationReport getApplicationId.

Prototype

@Public
@Stable
public abstract ApplicationId getApplicationId();

Source Link

Document

Get the ApplicationId of the application.

Usage

From source file:io.hops.hopsworks.common.jobs.flink.YarnClusterClient.java

License:Apache License

/**
 * Create a new Flink on YARN cluster.// www  . j av a2s. com
 *
 * @param clusterDescriptor The descriptor used at cluster creation
 * @param yarnClient Client to talk to YARN
 * @param appReport the YARN application ID
 * @param flinkConfig Flink configuration
 * @param sessionFilesDir Location of files required for YARN session
 * @param newlyCreatedCluster Indicator whether this cluster has just been
 * created
 * @throws IOException
 * @throws YarnException
 */
public YarnClusterClient(final AbstractYarnClusterDescriptor clusterDescriptor, final YarnClient yarnClient,
        final ApplicationReport appReport, org.apache.flink.configuration.Configuration flinkConfig,
        Path sessionFilesDir, boolean newlyCreatedCluster) throws IOException, YarnException {

    super(flinkConfig);

    this.akkaDuration = AkkaUtils.getTimeout(flinkConfig);
    this.clusterDescriptor = clusterDescriptor;
    this.yarnClient = yarnClient;
    this.hadoopConfig = yarnClient.getConfig();
    this.sessionFilesDir = sessionFilesDir;
    this.appReport = appReport;
    this.appId = appReport.getApplicationId();
    this.trackingURL = appReport.getTrackingUrl();
    this.newlyCreatedCluster = newlyCreatedCluster;

    this.applicationClient = new LazApplicationClientLoader(flinkConfig, actorSystemLoader);

    this.pollingRunner = new PollingThread(yarnClient, appId);
    this.pollingRunner.setDaemon(true);
    this.pollingRunner.start();

    Runtime.getRuntime().addShutdownHook(clientShutdownHook);
}

From source file:io.hops.hopsworks.common.jobs.flink.YarnClusterClient.java

License:Apache License

/**
 * Shuts down the Yarn application/*w  ww.j a  va 2  s .  c o  m*/
 */
public void shutdownCluster() {

    if (hasBeenShutDown.getAndSet(true)) {
        return;
    }

    if (!isConnected) {
        throw new IllegalStateException("The cluster has been not been connected to the ApplicationMaster.");
    }

    try {
        Runtime.getRuntime().removeShutdownHook(clientShutdownHook);
    } catch (IllegalStateException e) {
        // we are already in the shutdown hook
    }

    LOG.info("Sending shutdown request to the Application Master");
    try {
        Future<Object> response = Patterns.ask(applicationClient.get(), new YarnMessages.LocalStopYarnSession(
                getApplicationStatus(), "Flink YARN Client requested shutdown"), new Timeout(akkaDuration));
        Await.ready(response, akkaDuration);
    } catch (Exception e) {
        LOG.warn("Error while stopping YARN cluster.", e);
    }

    try {
        File propertiesFile = FlinkYarnSessionCli.getYarnPropertiesLocation(flinkConfig);
        if (propertiesFile.isFile()) {
            if (propertiesFile.delete()) {
                LOG.info("Deleted Yarn properties file at {}", propertiesFile.getAbsoluteFile().toString());
            } else {
                LOG.warn("Couldn't delete Yarn properties file at {}",
                        propertiesFile.getAbsoluteFile().toString());
            }
        }
    } catch (Exception e) {
        LOG.warn("Exception while deleting the JobManager address file", e);
    }

    if (sessionFilesDir != null) {
        LOG.info("Deleting files in " + sessionFilesDir);
        try {
            FileSystem shutFS = FileSystem.get(hadoopConfig);
            shutFS.delete(sessionFilesDir, true); // delete conf and jar file.
            shutFS.close();
        } catch (IOException e) {
            LOG.error("Could not delete the Flink jar and configuration files in HDFS..", e);
        }
    } else {
        LOG.warn("Session file directory not set. Not deleting session files");
    }

    try {
        pollingRunner.stopRunner();
        pollingRunner.join(1000);
    } catch (InterruptedException e) {
        LOG.warn("Shutdown of the polling runner was interrupted", e);
        Thread.currentThread().interrupt();
    }

    try {
        ApplicationReport appReport = yarnClient.getApplicationReport(appId);

        LOG.info("Application " + appId + " finished with state " + appReport.getYarnApplicationState()
                + " and final state " + appReport.getFinalApplicationStatus() + " at "
                + appReport.getFinishTime());

        if (appReport.getYarnApplicationState() == YarnApplicationState.FAILED
                || appReport.getYarnApplicationState() == YarnApplicationState.KILLED) {
            LOG.warn("Application failed. Diagnostics " + appReport.getDiagnostics());
            LOG.warn("If log aggregation is activated in the Hadoop cluster, we recommend to retrieve "
                    + "the full application log using this command:\n" + "\tyarn logs -appReport "
                    + appReport.getApplicationId() + "\n"
                    + "(It sometimes takes a few seconds until the logs are aggregated)");
        }
    } catch (Exception e) {
        LOG.warn("Couldn't get final report", e);
    }

    LOG.info("YARN Client is shutting down");
    yarnClient.stop(); // actorRunner is using the yarnClient.
    yarnClient = null; // set null to clearly see if somebody wants to access it afterwards.
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

License:Apache License

private SliderApp createSliderAppObject(ApplicationReport yarnApp, Set<String> properties,
        SliderClient sliderClient) {// w  w w  .j a  v  a 2  s  . c  o  m
    if (yarnApp == null) {
        return null;
    }

    SliderApp app = new SliderApp();
    app.setState(yarnApp.getYarnApplicationState().name());

    // Valid Slider App?
    // We want all Slider apps except the ones which properly finished.
    if (YarnApplicationState.FINISHED.equals(yarnApp.getYarnApplicationState())) {
        try {
            if (sliderClient.actionExists(yarnApp.getName(), false) == LauncherExitCodes.EXIT_SUCCESS) {
                app.setState(SliderApp.STATE_FROZEN);
            }
        } catch (UnknownApplicationInstanceException e) {
            return null; // Application not in HDFS - means it is not frozen
        } catch (YarnException e) {
            logger.warn("Unable to determine frozen state for " + yarnApp.getName(), e);
            return null;
        } catch (IOException e) {
            logger.warn("Unable to determine frozen state for " + yarnApp.getName(), e);
            return null;
        }
    }
    if (YarnApplicationState.KILLED.equals(yarnApp.getYarnApplicationState())
            || YarnApplicationState.FAILED.equals(yarnApp.getYarnApplicationState())) {
        try {
            if (sliderClient.actionExists(yarnApp.getName(), false) != LauncherExitCodes.EXIT_SUCCESS) {
                // YARN application is killed or failed, and no HDFS content - Application has been destroyed.
                return null;
            }
        } catch (UnknownApplicationInstanceException e) {
            return null; // Application not in HDFS - means it is not frozen
        } catch (YarnException e) {
            logger.warn("Unable to determine status of killed app " + yarnApp.getName(), e);
            return null;
        } catch (IOException e) {
            logger.warn("Unable to determine status of killed app " + yarnApp.getName(), e);
            return null;
        }
    }

    app.setId(getApplicationIdString(yarnApp.getApplicationId()));
    app.setName(yarnApp.getName());
    app.setUser(yarnApp.getUser());
    app.setDiagnostics(yarnApp.getDiagnostics());
    app.setYarnId(yarnApp.getApplicationId().toString());
    app.setStartTime(yarnApp.getStartTime());
    app.setEndTime(yarnApp.getFinishTime());
    Set<String> applicationTags = yarnApp.getApplicationTags();
    if (applicationTags != null && applicationTags.size() > 0) {
        for (String tag : applicationTags) {
            int index = tag.indexOf(':');
            if (index > 0 && index < tag.length() - 1) {
                String key = tag.substring(0, index).trim();
                String value = tag.substring(index + 1).trim();
                if ("name".equals(key)) {
                    app.setType(value);
                } else if ("version".equals(key)) {
                    app.setAppVersion(value);
                } else if ("description".equals(key)) {
                    app.setDescription(value);
                }
            }
        }
    }
    if (properties != null && !properties.isEmpty()) {
        SliderAppType matchedAppType = null;
        List<SliderAppType> matchingAppTypes = getSliderAppTypes(null);
        if (matchingAppTypes != null && matchingAppTypes.size() > 0) {
            for (SliderAppType appType : matchingAppTypes) {
                if ((appType.getTypeName() != null && appType.getTypeName().equalsIgnoreCase(app.getType()))
                        && (appType.getTypeVersion() != null
                                && appType.getTypeVersion().equalsIgnoreCase(app.getAppVersion()))) {
                    matchedAppType = appType;
                    break;
                }
            }
        }

        SliderAppMasterClient sliderAppClient = yarnApp.getTrackingUrl() == null ? null
                : new SliderAppMasterClient(yarnApp.getTrackingUrl());
        SliderAppMasterData appMasterData = null;
        Map<String, String> quickLinks = new HashMap<String, String>();
        Set<String> metrics = new HashSet<String>();
        for (String property : properties) {
            if ("RUNNING".equals(app.getState())) {
                if (sliderAppClient != null) {
                    if (appMasterData == null) {
                        appMasterData = sliderAppClient.getAppMasterData();
                    }
                    if (appMasterData != null && "urls".equals(property.toLowerCase())) {
                        if (quickLinks.isEmpty()) {
                            quickLinks = sliderAppClient.getQuickLinks(appMasterData.publisherUrl);
                        }
                        app.setUrls(quickLinks);
                    } else if (appMasterData != null && "configs".equals(property.toLowerCase())) {
                        Map<String, Map<String, String>> configs = sliderAppClient
                                .getConfigs(appMasterData.publisherUrl);
                        app.setConfigs(configs);
                    } else if (appMasterData != null && "jmx".equals(property.toLowerCase())) {
                        if (quickLinks.isEmpty()) {
                            quickLinks = sliderAppClient.getQuickLinks(appMasterData.publisherUrl);
                        }
                        if (quickLinks != null && quickLinks.containsKey("JMX")) {
                            String jmxUrl = quickLinks.get("JMX");
                            if (matchedAppType != null) {
                                MetricsHolder metricsHolder = appMetrics.get(matchedAppType.uniqueName());
                                app.setJmx(sliderAppClient.getJmx(jmxUrl, viewContext, matchedAppType,
                                        metricsHolder));
                            }
                        }
                        Map<String, Map<String, String>> configs = sliderAppClient
                                .getConfigs(appMasterData.publisherUrl);
                        app.setConfigs(configs);
                    } else if ("components".equals(property.toLowerCase())) {
                        try {
                            ClusterDescription description = sliderClient
                                    .getClusterDescription(yarnApp.getName());
                            if (description != null && description.status != null
                                    && !description.status.isEmpty()) {
                                Map<String, SliderAppComponent> componentTypeMap = new HashMap<String, SliderAppComponent>();
                                for (Entry<String, Object> e : description.status.entrySet()) {
                                    @SuppressWarnings("unchecked")
                                    Map<String, Map<String, Map<String, Object>>> componentsObj = (Map<String, Map<String, Map<String, Object>>>) e
                                            .getValue();
                                    boolean isLive = "live".equals(e.getKey());
                                    for (Entry<String, Map<String, Map<String, Object>>> componentEntry : componentsObj
                                            .entrySet()) {
                                        SliderAppComponent appComponent = componentTypeMap
                                                .get(componentEntry.getKey());
                                        if (appComponent == null) {
                                            appComponent = new SliderAppComponent();
                                            appComponent.setComponentName(componentEntry.getKey());
                                            appComponent.setActiveContainers(
                                                    new HashMap<String, Map<String, String>>());
                                            appComponent.setCompletedContainers(
                                                    new HashMap<String, Map<String, String>>());
                                            componentTypeMap.put(componentEntry.getKey(), appComponent);
                                        }
                                        for (Entry<String, Map<String, Object>> containerEntry : componentEntry
                                                .getValue().entrySet()) {
                                            Map<String, String> containerDataMap = new HashMap<String, String>();
                                            String containerId = containerEntry.getKey();
                                            Map<String, Object> containerValues = containerEntry.getValue();
                                            for (String containerProperty : containerValues.keySet()) {
                                                Object containerPropertyValue = containerValues
                                                        .get(containerProperty);
                                                containerDataMap.put(containerProperty,
                                                        containerPropertyValue.toString());
                                            }
                                            if (isLive) {
                                                appComponent.getActiveContainers().put(containerId,
                                                        containerDataMap);
                                            } else {
                                                appComponent.getCompletedContainers().put(containerId,
                                                        containerDataMap);
                                            }
                                        }
                                        // Set total instances count from statistics
                                        appComponent.setInstanceCount(appComponent.getActiveContainers().size()
                                                + appComponent.getCompletedContainers().size());
                                        if (description.statistics != null && description.statistics
                                                .containsKey(componentEntry.getKey())) {
                                            Map<String, Integer> statisticsMap = description.statistics
                                                    .get(componentEntry.getKey());
                                            if (statisticsMap.containsKey("containers.desired")) {
                                                appComponent.setInstanceCount(
                                                        statisticsMap.get("containers.desired"));
                                            }
                                        }
                                    }
                                }
                                app.setAlerts(
                                        sliderAlerts.generateComponentsAlerts(componentTypeMap, app.getType()));
                                app.setComponents(componentTypeMap);
                            }
                        } catch (UnknownApplicationInstanceException e) {
                            logger.warn("Unable to determine app components for " + yarnApp.getName(), e);
                        } catch (YarnException e) {
                            logger.warn("Unable to determine app components for " + yarnApp.getName(), e);
                            throw new RuntimeException(e.getMessage(), e);
                        } catch (IOException e) {
                            logger.warn("Unable to determine app components for " + yarnApp.getName(), e);
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    } else if (property.startsWith(METRICS_PREFIX)) {
                        metrics.add(property.substring(METRICS_PREFIX.length()));
                    } else if ("supportedMetrics".equals(property)) {
                        if (matchedAppType != null) {
                            app.setSupportedMetrics(matchedAppType.getSupportedMetrics());
                        }
                    }
                }
            }
        }
        if (metrics.size() > 0) {
            if (quickLinks.isEmpty()) {
                quickLinks = sliderAppClient.getQuickLinks(appMasterData.publisherUrl);
            }
            if (quickLinks != null && quickLinks.containsKey(METRICS_API_NAME)) {
                String metricsUrl = quickLinks.get(METRICS_API_NAME);
                MetricsHolder metricsHolder = appMetrics.get(matchedAppType.uniqueName());
                app.setMetrics(sliderAppClient.getMetrics(yarnApp.getName(), metricsUrl, metrics, null,
                        viewContext, matchedAppType, metricsHolder));
            }
        }
    }
    return app;
}

From source file:org.apache.flink.yarn.FlinkYarnCluster.java

License:Apache License

/**
 * Connect the FlinkYarnCluster to the ApplicationMaster.
 *
 * Detached YARN sessions don't need to connect to the ApplicationMaster.
 * Detached per job YARN sessions need to connect until the required number of TaskManagers have been started.
 * /*from  w w w .j  a  va2 s  . co m*/
 * @throws IOException
 */
public void connectToCluster() throws IOException {
    if (isConnected) {
        throw new IllegalStateException("Can not connect to the cluster again");
    }

    // start actor system
    LOG.info("Start actor system.");
    // find name of own public interface, able to connect to the JM
    // try to find address for 2 seconds. log after 400 ms.
    InetAddress ownHostname = ConnectionUtils.findConnectingAddress(jobManagerAddress, 2000, 400);
    actorSystem = AkkaUtils.createActorSystem(flinkConfig, new Some<Tuple2<String, Object>>(
            new Tuple2<String, Object>(ownHostname.getCanonicalHostName(), 0)));

    // Create the leader election service
    flinkConfig.setString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, this.jobManagerAddress.getHostName());
    flinkConfig.setInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, this.jobManagerAddress.getPort());

    LeaderRetrievalService leaderRetrievalService;

    try {
        leaderRetrievalService = LeaderRetrievalUtils.createLeaderRetrievalService(flinkConfig);
    } catch (Exception e) {
        throw new IOException("Could not create the leader retrieval service.", e);
    }

    // start application client
    LOG.info("Start application client.");

    applicationClient = actorSystem.actorOf(
            Props.create(ApplicationClient.class, flinkConfig, leaderRetrievalService), "applicationClient");

    actorRunner = new Thread(new Runnable() {
        @Override
        public void run() {
            // blocks until ApplicationClient has been stopped
            actorSystem.awaitTermination();

            // get final application report
            try {
                ApplicationReport appReport = yarnClient.getApplicationReport(appId);

                LOG.info("Application " + appId + " finished with state " + appReport.getYarnApplicationState()
                        + " and final state " + appReport.getFinalApplicationStatus() + " at "
                        + appReport.getFinishTime());

                if (appReport.getYarnApplicationState() == YarnApplicationState.FAILED
                        || appReport.getYarnApplicationState() == YarnApplicationState.KILLED) {
                    LOG.warn("Application failed. Diagnostics " + appReport.getDiagnostics());
                    LOG.warn("If log aggregation is activated in the Hadoop cluster, we recommend to retrieve "
                            + "the full application log using this command:\n" + "\tyarn logs -applicationId "
                            + appReport.getApplicationId() + "\n"
                            + "(It sometimes takes a few seconds until the logs are aggregated)");
                }
            } catch (Exception e) {
                LOG.warn("Error while getting final application report", e);
            }
        }
    });
    actorRunner.setDaemon(true);
    actorRunner.start();

    pollingRunner = new PollingThread(yarnClient, appId);
    pollingRunner.setDaemon(true);
    pollingRunner.start();

    Runtime.getRuntime().addShutdownHook(clientShutdownHook);

    isConnected = true;
}

From source file:org.apache.flink.yarn.Flip6YarnClusterDescriptor.java

License:Apache License

@Override
protected ClusterClient<ApplicationId> createYarnClusterClient(AbstractYarnClusterDescriptor descriptor,
        int numberTaskManagers, int slotsPerTaskManager, ApplicationReport report,
        Configuration flinkConfiguration, boolean perJobCluster) throws Exception {
    return new RestClusterClient<>(flinkConfiguration, report.getApplicationId());
}

From source file:org.apache.flink.yarn.YarnClusterClient.java

License:Apache License

/**
 * Shuts down the Yarn application//from w ww  .  java 2s  . c  o  m
 */
public void shutdownCluster() {

    if (hasBeenShutDown.getAndSet(true)) {
        return;
    }

    if (!isConnected) {
        throw new IllegalStateException("The cluster has been not been connected to the ApplicationMaster.");
    }

    try {
        Runtime.getRuntime().removeShutdownHook(clientShutdownHook);
    } catch (IllegalStateException e) {
        // we are already in the shutdown hook
    }

    LOG.info("Sending shutdown request to the Application Master");
    try {
        Future<Object> response = Patterns.ask(applicationClient.get(), new YarnMessages.LocalStopYarnSession(
                getApplicationStatus(), "Flink YARN Client requested shutdown"), new Timeout(akkaDuration));
        Await.ready(response, akkaDuration);
    } catch (Exception e) {
        LOG.warn("Error while stopping YARN cluster.", e);
    }

    try {
        File propertiesFile = FlinkYarnSessionCli.getYarnPropertiesLocation(flinkConfig);
        if (propertiesFile.isFile()) {
            if (propertiesFile.delete()) {
                LOG.info("Deleted Yarn properties file at {}", propertiesFile.getAbsoluteFile().toString());
            } else {
                LOG.warn("Couldn't delete Yarn properties file at {}",
                        propertiesFile.getAbsoluteFile().toString());
            }
        }
    } catch (Exception e) {
        LOG.warn("Exception while deleting the JobManager address file", e);
    }

    if (sessionFilesDir != null) {
        LOG.info("Deleting files in " + sessionFilesDir);
        try {
            FileSystem shutFS = FileSystem.get(hadoopConfig);
            shutFS.delete(sessionFilesDir, true); // delete conf and jar file.
            shutFS.close();
        } catch (IOException e) {
            LOG.error("Could not delete the Flink jar and configuration files in HDFS..", e);
        }
    } else {
        LOG.warn("Session file directory not set. Not deleting session files");
    }

    try {
        pollingRunner.stopRunner();
        pollingRunner.join(1000);
    } catch (InterruptedException e) {
        LOG.warn("Shutdown of the polling runner was interrupted", e);
        Thread.currentThread().interrupt();
    }

    try {
        ApplicationReport appReport = yarnClient.getApplicationReport(appId);

        LOG.info("Application " + appId + " finished with state " + appReport.getYarnApplicationState()
                + " and final state " + appReport.getFinalApplicationStatus() + " at "
                + appReport.getFinishTime());

        if (appReport.getYarnApplicationState() == YarnApplicationState.FAILED
                || appReport.getYarnApplicationState() == YarnApplicationState.KILLED) {
            LOG.warn("Application failed. Diagnostics " + appReport.getDiagnostics());
            LOG.warn("If log aggregation is activated in the Hadoop cluster, we recommend to retrieve "
                    + "the full application log using this command:" + System.lineSeparator()
                    + "\tyarn logs -applicationId " + appReport.getApplicationId() + System.lineSeparator()
                    + "(It sometimes takes a few seconds until the logs are aggregated)");
        }
    } catch (Exception e) {
        LOG.warn("Couldn't get final report", e);
    }

    LOG.info("YARN Client is shutting down");
    yarnClient.stop(); // actorRunner is using the yarnClient.
    yarnClient = null; // set null to clearly see if somebody wants to access it afterwards.
}

From source file:org.apache.flink.yarn.YarnClusterClientV2.java

License:Apache License

@Override
protected JobSubmissionResult submitJob(JobGraph jobGraph, ClassLoader classLoader)
        throws ProgramInvocationException {
    try {/*  w ww  . j av a 2 s . co m*/
        // Create application via yarnClient
        final YarnClientApplication yarnApplication = yarnClient.createApplication();
        ApplicationReport report = this.clusterDescriptor.startAppMaster(jobGraph, yarnClient, yarnApplication);
        if (report.getYarnApplicationState().equals(YarnApplicationState.RUNNING)) {
            appId = report.getApplicationId();
            trackingURL = report.getTrackingUrl();
            logAndSysout("Please refer to " + getWebInterfaceURL() + " for the running status of job "
                    + jobGraph.getJobID().toString());
            //TODO: not support attach mode now
            return new JobSubmissionResult(jobGraph.getJobID());
        } else {
            throw new ProgramInvocationException("Fail to submit the job.");
        }
    } catch (Exception e) {
        throw new ProgramInvocationException("Fail to submit the job", e.getCause());
    }
}

From source file:org.apache.flink.yarn.YARNSessionCapacitySchedulerITCase.java

License:Apache License

private void testDetachedPerJobYarnClusterInternal(String job) {
    YarnClient yc = YarnClient.createYarnClient();
    yc.init(yarnConfiguration);/*www .j  a v  a 2 s  .  co  m*/
    yc.start();

    // get temporary folder for writing output of wordcount example
    File tmpOutFolder = null;
    try {
        tmpOutFolder = tmp.newFolder();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // get temporary file for reading input data for wordcount example
    File tmpInFile;
    try {
        tmpInFile = tmp.newFile();
        FileUtils.writeStringToFile(tmpInFile, WordCountData.TEXT);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    Runner runner = startWithArgs(
            new String[] { "run", "-m", "yarn-cluster", "-yj", flinkUberjar.getAbsolutePath(), "-yt",
                    flinkLibFolder.getAbsolutePath(), "-yn", "1", "-yjm", "768", "-yD",
                    "yarn.heap-cutoff-ratio=0.5", // test if the cutoff is passed correctly
                    "-ytm", "1024", "-ys", "2", // test requesting slots from YARN.
                    "--yarndetached", job, "--input", tmpInFile.getAbsoluteFile().toString(), "--output",
                    tmpOutFolder.getAbsoluteFile().toString() },
            "Job has been submitted with JobID", RunTypes.CLI_FRONTEND);

    // it should usually be 2, but on slow machines, the number varies
    Assert.assertTrue("There should be at most 2 containers running", getRunningContainers() <= 2);
    // give the runner some time to detach
    for (int attempt = 0; runner.isAlive() && attempt < 5; attempt++) {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
        }
    }
    Assert.assertFalse("The runner should detach.", runner.isAlive());
    LOG.info("CLI Frontend has returned, so the job is running");

    // find out the application id and wait until it has finished.
    try {
        List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING));

        ApplicationId tmpAppId;
        if (apps.size() == 1) {
            // Better method to find the right appId. But sometimes the app is shutting down very fast
            // Only one running
            tmpAppId = apps.get(0).getApplicationId();

            LOG.info("waiting for the job with appId {} to finish", tmpAppId);
            // wait until the app has finished
            while (yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING)).size() > 0) {
                sleep(500);
            }
        } else {
            // get appId by finding the latest finished appid
            apps = yc.getApplications();
            Collections.sort(apps, new Comparator<ApplicationReport>() {
                @Override
                public int compare(ApplicationReport o1, ApplicationReport o2) {
                    return o1.getApplicationId().compareTo(o2.getApplicationId()) * -1;
                }
            });
            tmpAppId = apps.get(0).getApplicationId();
            LOG.info("Selected {} as the last appId from {}", tmpAppId, Arrays.toString(apps.toArray()));
        }
        final ApplicationId id = tmpAppId;

        // now it has finished.
        // check the output files.
        File[] listOfOutputFiles = tmpOutFolder.listFiles();

        Assert.assertNotNull("Taskmanager output not found", listOfOutputFiles);
        LOG.info("The job has finished. TaskManager output files found in {}", tmpOutFolder);

        // read all output files in output folder to one output string
        String content = "";
        for (File f : listOfOutputFiles) {
            if (f.isFile()) {
                content += FileUtils.readFileToString(f) + "\n";
            }
        }
        //String content = FileUtils.readFileToString(taskmanagerOut);
        // check for some of the wordcount outputs.
        Assert.assertTrue("Expected string 'da 5' or '(all,2)' not found in string '" + content + "'",
                content.contains("da 5") || content.contains("(da,5)") || content.contains("(all,2)"));
        Assert.assertTrue("Expected string 'der 29' or '(mind,1)' not found in string'" + content + "'",
                content.contains("der 29") || content.contains("(der,29)") || content.contains("(mind,1)"));

        // check if the heap size for the TaskManager was set correctly
        File jobmanagerLog = YarnTestBase.findFile("..", new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.contains("jobmanager.log") && dir.getAbsolutePath().contains(id.toString());
            }
        });
        Assert.assertNotNull("Unable to locate JobManager log", jobmanagerLog);
        content = FileUtils.readFileToString(jobmanagerLog);
        // TM was started with 1024 but we cut off 50% (NOT THE DEFAULT VALUE)
        String expected = "Starting TaskManagers with command: $JAVA_HOME/bin/java -Xms424m -Xmx424m";
        Assert.assertTrue(
                "Expected string '" + expected + "' not found in JobManager log: '" + jobmanagerLog + "'",
                content.contains(expected));
        expected = " (2/2) (attempt #0) to ";
        Assert.assertTrue("Expected string '" + expected + "' not found in JobManager log."
                + "This string checks that the job has been started with a parallelism of 2. Log contents: '"
                + jobmanagerLog + "'", content.contains(expected));

        // make sure the detached app is really finished.
        LOG.info("Checking again that app has finished");
        ApplicationReport rep;
        do {
            sleep(500);
            rep = yc.getApplicationReport(id);
            LOG.info("Got report {}", rep);
        } while (rep.getYarnApplicationState() == YarnApplicationState.RUNNING);

    } catch (Throwable t) {
        LOG.warn("Error while detached yarn session was running", t);
        Assert.fail(t.getMessage());
    }
}

From source file:org.apache.flink.yarn.YARNSessionFIFOITCase.java

License:Apache License

/**
 * Test regular operation, including command line parameter parsing.
 *//*from w  w  w.ja v a 2  s.c  om*/
@Test(timeout = 60000) // timeout after a minute.
public void testDetachedMode() {
    LOG.info("Starting testDetachedMode()");
    addTestAppender(FlinkYarnSessionCli.class, Level.INFO);
    Runner runner = startWithArgs(new String[] { "-j", flinkUberjar.getAbsolutePath(), "-t",
            flinkLibFolder.getAbsolutePath(), "-n", "1", "-jm", "768", "-tm", "1024", "--name", "MyCustomName", // test setting a custom name
            "--detached" }, "Flink JobManager is now running on", RunTypes.YARN_SESSION);

    checkForLogString("The Flink YARN client has been started in detached mode");

    Assert.assertFalse("The runner should detach.", runner.isAlive());

    LOG.info("Waiting until two containers are running");
    // wait until two containers are running
    while (getRunningContainers() < 2) {
        sleep(500);
    }
    LOG.info("Two containers are running. Killing the application");

    // kill application "externally".
    try {
        YarnClient yc = YarnClient.createYarnClient();
        yc.init(yarnConfiguration);
        yc.start();
        List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING));
        Assert.assertEquals(1, apps.size()); // Only one running
        ApplicationReport app = apps.get(0);

        Assert.assertEquals("MyCustomName", app.getName());
        ApplicationId id = app.getApplicationId();
        yc.killApplication(id);

        while (yc.getApplications(EnumSet.of(YarnApplicationState.KILLED)).size() == 0) {
            sleep(500);
        }
    } catch (Throwable t) {
        LOG.warn("Killing failed", t);
        Assert.fail();
    }

    LOG.info("Finished testDetachedMode()");
}

From source file:org.apache.flink.yarn.YarnTestBase.java

License:Apache License

@Before
public void checkClusterEmpty() throws IOException, YarnException {
    if (yarnClient == null) {
        yarnClient = YarnClient.createYarnClient();
        yarnClient.init(yarnConfiguration);
        yarnClient.start();/*from   w w w .  j  a v  a  2 s. c o  m*/
    }

    List<ApplicationReport> apps = yarnClient.getApplications();
    for (ApplicationReport app : apps) {
        if (app.getYarnApplicationState() != YarnApplicationState.FINISHED
                && app.getYarnApplicationState() != YarnApplicationState.KILLED
                && app.getYarnApplicationState() != YarnApplicationState.FAILED) {
            Assert.fail("There is at least one application on the cluster is not finished." + "App "
                    + app.getApplicationId() + " is in state " + app.getYarnApplicationState());
        }
    }
}