Example usage for org.apache.hadoop.yarn.util ConverterUtils toString

List of usage examples for org.apache.hadoop.yarn.util ConverterUtils toString

Introduction

In this page you can find the example usage for org.apache.hadoop.yarn.util ConverterUtils toString.

Prototype

@Public
    @Deprecated
    public static String toString(ContainerId cId) 

Source Link

Usage

From source file:com.mellanox.hadoop.mapred.UdaPluginSH.java

License:Apache License

static IndexRecordBridge getPathIndex(String jobIDStr, String mapId, int reduce) {
    String user = userRsrc.get(jobIDStr);

    ///////////////////////
    JobID jobID = JobID.forName(jobIDStr);
    ApplicationId appID = ApplicationId.newInstance(Long.parseLong(jobID.getJtIdentifier()), jobID.getId());
    final String base = ContainerLocalizer.USERCACHE + "/" + user + "/" + ContainerLocalizer.APPCACHE + "/"
            + ConverterUtils.toString(appID) + "/output" + "/" + mapId;
    if (LOG.isDebugEnabled()) {
        LOG.debug("DEBUG0 " + base);
    }/*ww w.ja  va2 s .co  m*/
    // Index file
    IndexRecordBridge data = null;
    try {
        Path indexFileName = lDirAlloc.getLocalPathToRead(base + "/file.out.index", mjobConf);
        // Map-output file
        Path mapOutputFileName = lDirAlloc.getLocalPathToRead(base + "/file.out", mjobConf);
        if (LOG.isDebugEnabled()) {
            LOG.debug("DEBUG1 " + base + " : " + mapOutputFileName + " : " + indexFileName);
        }

        ///////////////////////
        // TODO: is this correct ?? - why user and not runAsUserName like in hadoop-1 ?? 
        // on 2nd thought, this sounds correct, because probably we registered the runAsUser and not the "user"
        data = indexCache.getIndexInformationBridge(mapId, reduce, indexFileName, user);
        data.pathMOF = mapOutputFileName.toString();
    } catch (IOException e) {
        LOG.error("got an exception while retrieving the Index Info");
    }

    return data;

}

From source file:org.apache.samza.job.yarn.ContainerUtil.java

License:Apache License

public void runContainer(int samzaContainerId, Container container) {
    String containerIdStr = ConverterUtils.toString(container.getId());
    log.info("Got available container ID ({}) for container: {}", samzaContainerId, container);

    String cmdBuilderClassName;/*ww  w .  j a v a 2  s.  c o m*/
    if (taskConfig.getCommandClass().isDefined()) {
        cmdBuilderClassName = taskConfig.getCommandClass().get();
    } else {
        cmdBuilderClassName = ShellCommandBuilder.class.getName();
    }
    CommandBuilder cmdBuilder = (CommandBuilder) Util.getObj(cmdBuilderClassName);
    cmdBuilder.setConfig(config).setId(samzaContainerId).setUrl(state.coordinatorUrl);

    String command = cmdBuilder.buildCommand();
    log.info("Container ID {} using command {}", samzaContainerId, command);

    log.info("Container ID {} using environment variables: ", samzaContainerId);
    Map<String, String> env = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : cmdBuilder.buildEnvironment().entrySet()) {
        String escapedValue = Util.envVarEscape(entry.getValue());
        env.put(entry.getKey(), escapedValue);
        log.info("{}={} ", entry.getKey(), escapedValue);
    }

    Path path = new Path(yarnConfig.getPackagePath());
    log.info("Starting container ID {} using package path {}", samzaContainerId, path);

    startContainer(path, container, env, getFormattedCommand(ApplicationConstants.LOG_DIR_EXPANSION_VAR,
            command, ApplicationConstants.STDOUT, ApplicationConstants.STDERR));

    if (state.neededContainers.decrementAndGet() == 0) {
        state.jobHealthy.set(true);
    }
    state.runningContainers.put(samzaContainerId, new YarnContainer(container));

    log.info("Claimed container ID {} for container {} on node {} (http://{}/node/containerlogs/{}).",
            new Object[] { samzaContainerId, containerIdStr, container.getNodeId().getHost(),
                    container.getNodeHttpAddress(), containerIdStr });

    log.info("Started container ID {}", samzaContainerId);
}

From source file:org.apache.samza.job.yarn.refactor.YarnContainerRunner.java

License:Apache License

/**
 * Runs a process as specified by the command builder on the container.
 * @param samzaContainerId id of the samza Container to run (passed as a command line parameter to the process)
 * @param container the samza container to run.
 * @param cmdBuilder the command builder that encapsulates the command, and the context
 *
 * @throws SamzaContainerLaunchException  when there's an exception in submitting the request to the RM.
 *
 *//*from  w ww  . j  a v a2  s .co  m*/
//TODO: we don't need samzaContainerId as a param here.
public void runContainer(int samzaContainerId, Container container, CommandBuilder cmdBuilder)
        throws SamzaContainerLaunchException {
    String containerIdStr = ConverterUtils.toString(container.getId());
    log.info("Got available container ID ({}) for container: {}", samzaContainerId, container);

    // check if we have framework path specified. If yes - use it, if not use default ./__package/
    String jobLib = ""; // in case of separate framework, this directory will point at the job's libraries
    String cmdPath = "./__package/";

    String fwkPath = JobConfig.getFwkPath(config);
    if (fwkPath != null && (!fwkPath.isEmpty())) {
        cmdPath = fwkPath;
        jobLib = "export JOB_LIB_DIR=./__package/lib";
    }
    log.info("In runContainer in util: fwkPath= " + fwkPath + ";cmdPath=" + cmdPath + ";jobLib=" + jobLib);
    cmdBuilder.setCommandPath(cmdPath);

    String command = cmdBuilder.buildCommand();
    log.info("Container ID {} using command {}", samzaContainerId, command);

    Map<String, String> env = getEscapedEnvironmentVariablesMap(cmdBuilder);
    printContainerEnvironmentVariables(samzaContainerId, env);

    log.info("Samza FWK path: " + command + "; env=" + env);

    Path path = new Path(yarnConfig.getPackagePath());
    log.info("Starting container ID {} using package path {}", samzaContainerId, path);

    startContainer(path, container, env, getFormattedCommand(ApplicationConstants.LOG_DIR_EXPANSION_VAR, jobLib,
            command, ApplicationConstants.STDOUT, ApplicationConstants.STDERR));

    log.info("Claimed container ID {} for container {} on node {} (http://{}/node/containerlogs/{}).",
            new Object[] { samzaContainerId, containerIdStr, container.getNodeId().getHost(),
                    container.getNodeHttpAddress(), containerIdStr });

    log.info("Started container ID {}", samzaContainerId);
}

From source file:org.apache.samza.job.yarn.SamzaTaskManager.java

License:Apache License

/**
 * This methods handles the onContainerCompleted callback from the RM. Based on the ContainerExitStatus, it decides
 * whether a container that exited is marked as complete or failure.
 *//*  w  ww.j  a  v a 2 s. com*/
@Override
public void onContainerCompleted(ContainerStatus containerStatus) {
    String containerIdStr = ConverterUtils.toString(containerStatus.getContainerId());
    int containerId = -1;
    for (Map.Entry<Integer, YarnContainer> entry : state.runningContainers.entrySet()) {
        if (entry.getValue().id().equals(containerStatus.getContainerId())) {
            containerId = entry.getKey();
            break;
        }
    }
    state.runningContainers.remove(containerId);

    int exitStatus = containerStatus.getExitStatus();
    switch (exitStatus) {
    case ContainerExitStatus.SUCCESS:
        log.info("Container {} completed successfully.", containerIdStr);

        state.completedContainers.incrementAndGet();

        if (containerId != -1) {
            state.finishedContainers.add(containerId);
            containerFailures.remove(containerId);
        }

        if (state.completedContainers.get() == state.containerCount) {
            log.info("Setting job status to SUCCEEDED, since all containers have been marked as completed.");
            state.status = FinalApplicationStatus.SUCCEEDED;
        }
        break;

    case ContainerExitStatus.DISKS_FAILED:
    case ContainerExitStatus.ABORTED:
    case ContainerExitStatus.PREEMPTED:
        log.info(
                "Got an exit code of {}. This means that container {} was "
                        + "killed by YARN, either due to being released by the application "
                        + "master or being 'lost' due to node failures etc. or due to preemption by the RM",
                exitStatus, containerIdStr);

        state.releasedContainers.incrementAndGet();

        // If this container was assigned some partitions (a containerId), then
        // clean up, and request a new container for the tasks. This only
        // should happen if the container was 'lost' due to node failure, not
        // if the AM released the container.
        if (containerId != -1) {
            log.info(
                    "Released container {} was assigned task group ID {}. Requesting a new container for the task group.",
                    containerIdStr, containerId);

            state.neededContainers.incrementAndGet();
            state.jobHealthy.set(false);

            // request a container on new host
            containerAllocator.requestContainer(containerId, ContainerAllocator.ANY_HOST);
        }
        break;

    default:
        // TODO: Handle failure more intelligently. Should track NodeFailures!
        log.info("Container failed for some reason. Let's start it again");
        log.info("Container " + containerIdStr + " failed with exit code " + exitStatus + " - "
                + containerStatus.getDiagnostics());

        state.failedContainers.incrementAndGet();
        state.failedContainersStatus.put(containerIdStr, containerStatus);
        state.jobHealthy.set(false);

        if (containerId != -1) {
            state.neededContainers.incrementAndGet();
            // Find out previously running container location
            String lastSeenOn = state.jobCoordinator.jobModel().getContainerToHostValue(containerId,
                    SetContainerHostMapping.HOST_KEY);
            if (!hostAffinityEnabled || lastSeenOn == null) {
                lastSeenOn = ContainerAllocator.ANY_HOST;
            }
            // A container failed for an unknown reason. Let's check to see if
            // we need to shutdown the whole app master if too many container
            // failures have happened. The rules for failing are that the
            // failure count for a task group id must be > the configured retry
            // count, and the last failure (the one prior to this one) must have
            // happened less than retry window ms ago. If retry count is set to
            // 0, the app master will fail on any container failure. If the
            // retry count is set to a number < 0, a container failure will
            // never trigger an app master failure.
            int retryCount = yarnConfig.getContainerRetryCount();
            int retryWindowMs = yarnConfig.getContainerRetryWindowMs();

            if (retryCount == 0) {
                log.error(
                        "Container ID {} ({}) failed, and retry count is set to 0, so shutting down the application master, and marking the job as failed.",
                        containerId, containerIdStr);

                tooManyFailedContainers = true;
            } else if (retryCount > 0) {
                int currentFailCount;
                long lastFailureTime;
                if (containerFailures.containsKey(containerId)) {
                    ContainerFailure failure = containerFailures.get(containerId);
                    currentFailCount = failure.getCount() + 1;
                    lastFailureTime = failure.getLastFailure();
                } else {
                    currentFailCount = 1;
                    lastFailureTime = 0L;
                }
                if (currentFailCount >= retryCount) {
                    long lastFailureMsDiff = System.currentTimeMillis() - lastFailureTime;

                    if (lastFailureMsDiff < retryWindowMs) {
                        log.error("Container ID " + containerId + "(" + containerIdStr + ") has failed "
                                + currentFailCount + " times, with last failure " + lastFailureMsDiff
                                + "ms ago. This is greater than retry count of " + retryCount
                                + " and window of " + retryWindowMs
                                + "ms , so shutting down the application master, and marking the job as failed.");

                        // We have too many failures, and we're within the window
                        // boundary, so reset shut down the app master.
                        tooManyFailedContainers = true;
                        state.status = FinalApplicationStatus.FAILED;
                    } else {
                        log.info(
                                "Resetting fail count for container ID {} back to 1, since last container failure ({}) for "
                                        + "this container ID was outside the bounds of the retry window.",
                                containerId, containerIdStr);

                        // Reset counter back to 1, since the last failure for this
                        // container happened outside the window boundary.
                        containerFailures.put(containerId, new ContainerFailure(1, System.currentTimeMillis()));
                    }
                } else {
                    log.info("Current fail count for container ID {} is {}.", containerId, currentFailCount);
                    containerFailures.put(containerId,
                            new ContainerFailure(currentFailCount, System.currentTimeMillis()));
                }
            }

            if (!tooManyFailedContainers) {
                // Request a new container
                containerAllocator.requestContainer(containerId, lastSeenOn);
            }
        }

    }
}

From source file:org.apache.samza.job.yarn.YarnClusterResourceManager.java

License:Apache License

/**
 * Runs a process as specified by the command builder on the container.
 * @param processorId id of the samza processor to run (passed as a command line parameter to the process)
 * @param container the yarn container to run the processor on.
 * @param cmdBuilder the command builder that encapsulates the command, and the context
 * @throws IOException on IO exceptions running the container
 *//* w  ww  .  j  a  v  a  2 s .  c o  m*/
public void runProcessor(String processorId, Container container, CommandBuilder cmdBuilder)
        throws IOException {
    String containerIdStr = ConverterUtils.toString(container.getId());
    // check if we have framework path specified. If yes - use it, if not use default ./__package/
    String jobLib = ""; // in case of separate framework, this directory will point at the job's libraries
    String cmdPath = "./__package/";

    String fwkPath = JobConfig.getFwkPath(this.config);
    if (fwkPath != null && (!fwkPath.isEmpty())) {
        cmdPath = fwkPath;
        jobLib = "export JOB_LIB_DIR=./__package/lib";
    }
    cmdBuilder.setCommandPath(cmdPath);
    String command = cmdBuilder.buildCommand();

    Map<String, String> env = getEscapedEnvironmentVariablesMap(cmdBuilder);
    env.put(ShellCommandConfig.ENV_EXECUTION_ENV_CONTAINER_ID(),
            Util.envVarEscape(container.getId().toString()));

    Path packagePath = new Path(yarnConfig.getPackagePath());
    String formattedCommand = getFormattedCommand(ApplicationConstants.LOG_DIR_EXPANSION_VAR, jobLib, command,
            ApplicationConstants.STDOUT, ApplicationConstants.STDERR);

    log.info(
            "Running Processor ID: {} on Container ID: {} on host: {} using command: {} and env: {} and package path: {}",
            processorId, containerIdStr, container.getNodeHttpAddress(), formattedCommand, env, packagePath);
    state.pendingProcessors.put(processorId, new YarnContainer(container));

    startContainer(packagePath, container, env, formattedCommand);

    log.info(
            "Made start request for Processor ID: {} on Container ID: {} on host: {} (http://{}/node/containerlogs/{}).",
            processorId, containerIdStr, container.getNodeId().getHost(), container.getNodeHttpAddress(),
            containerIdStr);
}

From source file:org.apache.samza.job.yarn.YarnContainerRunner.java

License:Apache License

/**
 * Runs a process as specified by the command builder on the container.
 * @param samzaContainerId id of the samza Container to run (passed as a command line parameter to the process)
 * @param container the samza container to run.
 * @param cmdBuilder the command builder that encapsulates the command, and the context
 *
 * @throws SamzaContainerLaunchException  when there's an exception in submitting the request to the RM.
 *
 *//*from ww  w .  j  a v  a2 s.c  om*/
public void runContainer(String samzaContainerId, Container container, CommandBuilder cmdBuilder)
        throws SamzaContainerLaunchException {
    String containerIdStr = ConverterUtils.toString(container.getId());
    log.info("Got available container ID ({}) for container: {}", samzaContainerId, container);

    // check if we have framework path specified. If yes - use it, if not use default ./__package/
    String jobLib = ""; // in case of separate framework, this directory will point at the job's libraries
    String cmdPath = "./__package/";

    String fwkPath = JobConfig.getFwkPath(config);
    if (fwkPath != null && (!fwkPath.isEmpty())) {
        cmdPath = fwkPath;
        jobLib = "export JOB_LIB_DIR=./__package/lib";
    }
    log.info("In runContainer in util: fwkPath= " + fwkPath + ";cmdPath=" + cmdPath + ";jobLib=" + jobLib);
    cmdBuilder.setCommandPath(cmdPath);

    String command = cmdBuilder.buildCommand();
    log.info("Container ID {} using command {}", samzaContainerId, command);

    Map<String, String> env = getEscapedEnvironmentVariablesMap(cmdBuilder);
    env.put(ShellCommandConfig.ENV_EXECUTION_ENV_CONTAINER_ID(),
            Util.envVarEscape(container.getId().toString()));
    printContainerEnvironmentVariables(samzaContainerId, env);

    log.info("Samza FWK path: " + command + "; env=" + env);

    Path packagePath = new Path(yarnConfig.getPackagePath());
    log.info("Starting container ID {} using package path {}", samzaContainerId, packagePath);

    startContainer(packagePath, container, env, getFormattedCommand(ApplicationConstants.LOG_DIR_EXPANSION_VAR,
            jobLib, command, ApplicationConstants.STDOUT, ApplicationConstants.STDERR));

    log.info("Claimed container ID {} for container {} on node {} (http://{}/node/containerlogs/{}).",
            new Object[] { samzaContainerId, containerIdStr, container.getNodeId().getHost(),
                    container.getNodeHttpAddress(), containerIdStr });

    log.info("Started container ID {}", samzaContainerId);
}

From source file:org.springframework.yarn.am.container.DefaultContainerLauncher.java

License:Apache License

@Override
public void launchContainer(Container container, List<String> commands) {
    if (log.isDebugEnabled()) {
        log.debug("Launching container: " + container);
    }/*from  w ww.j  ava2 s.  c  om*/

    ContainerLaunchContext ctx = Records.newRecord(ContainerLaunchContext.class);
    String stagingId = container.getId().getApplicationAttemptId().getApplicationId().toString();
    getResourceLocalizer().setStagingId(stagingId);
    ctx.setLocalResources(getResourceLocalizer().getResources());
    ctx.setCommands(commands);

    // Yarn doesn't tell container what is its container id
    // so we do it here
    Map<String, String> env = getEnvironment();
    env.put(YarnSystemConstants.SYARN_CONTAINER_ID, ConverterUtils.toString(container.getId()));
    ctx.setEnvironment(env);
    ctx = getInterceptors().preLaunch(container, ctx);

    StartContainerRequest startContainerRequest = Records.newRecord(StartContainerRequest.class);
    startContainerRequest.setContainerLaunchContext(ctx);
    startContainerRequest.setContainerToken(container.getContainerToken());

    StartContainersRequest startContainersRequest = Records.newRecord(StartContainersRequest.class);
    ArrayList<StartContainerRequest> startContainerRequestList = new ArrayList<StartContainerRequest>();
    startContainerRequestList.add(startContainerRequest);
    startContainersRequest.setStartContainerRequests(startContainerRequestList);

    StartContainersResponse startContainersResponse = getCmTemplate(container)
            .startContainers(startContainersRequest);
    Map<ContainerId, SerializedException> failedRequests = startContainersResponse.getFailedRequests();
    List<ContainerId> successfullyStartedContainers = startContainersResponse
            .getSuccessfullyStartedContainers();
    // TODO: handle failed/success

    // notify interested parties of new launched container
    if (getYarnEventPublisher() != null) {
        getYarnEventPublisher().publishContainerLaunched(this, container);
    }
}

From source file:org.springframework.yarn.am.monitor.DefaultContainerMonitor.java

License:Apache License

@Override
public void reportContainer(Container container) {
    if (log.isDebugEnabled()) {
        log.debug("Reporting container=" + container);
    }/* w  ww  .  ja v  a2 s  .c  o m*/

    String cid = ConverterUtils.toString(container.getId());
    allocated.add(cid);

    if (log.isDebugEnabled()) {
        log.debug("State after reportContainer: " + toDebugString());
    }
}

From source file:org.springframework.yarn.am.monitor.DefaultContainerMonitor.java

License:Apache License

private void handleContainerStatus(List<ContainerStatus> containerStatuses, boolean notifyIntermediates) {
    for (ContainerStatus status : containerStatuses) {

        if (log.isDebugEnabled()) {
            log.debug("Reporting containerStatus=" + status);
        }//from  w  ww.ja  va2s .  com

        ContainerId containerId = status.getContainerId();
        int exitStatus = status.getExitStatus();
        ContainerState state = status.getState();
        String cid = ConverterUtils.toString(containerId);

        synchronized (lock) {
            if (state.equals(ContainerState.COMPLETE)) {
                if (exitStatus > 0) {
                    failed.add(cid);
                } else {
                    completed.add(cid);
                }
            }
            allocated.remove(cid);
            running.remove(cid);
        }

        if (notifyIntermediates) {
            dispatchCurrentContainerMonitorState();
        }
    }
    if (!notifyIntermediates) {
        dispatchCurrentContainerMonitorState();
    }
    if (log.isDebugEnabled()) {
        log.debug("State after handleContainerStatus: " + toDebugString());
    }
}

From source file:org.springframework.yarn.examples.AbstractManagedContainerGroupsAppmaster.java

License:Apache License

protected void handleContainerFailed(ContainerId containerId) {
    if (!onContainerFailed(containerId)) {
        log.info("XXX removing failed member " + ConverterUtils.toString(containerId));
        managedGroups.removeContainerNode(ConverterUtils.toString(containerId));
    }/*from   w  ww. j  a  v a2  s. co  m*/
}