Example usage for org.apache.hadoop.yarn.api.records Resource newInstance

List of usage examples for org.apache.hadoop.yarn.api.records Resource newInstance

Introduction

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

Prototype

@Public
    @Stable
    public static Resource newInstance(long memory, int vCores) 

Source Link

Usage

From source file:x10.x10rt.yarn.ApplicationMaster.java

License:Open Source License

private void processMessage(ByteBuffer msg, SocketChannel sc) {
    assert (msg.capacity() >= headerLength);

    msg.rewind(); // reset the buffer for reading from the beginning
    CTRL_MSG_TYPE type = CTRL_MSG_TYPE.values()[msg.getInt()];
    int destination = msg.getInt();
    final int source = msg.getInt();
    int datalen = msg.getInt();
    assert (datalen == msg.remaining());

    LOG.info("Processing message of type " + type + ", size " + (headerLength + datalen) + " from place "
            + source);// ww w  . ja v  a  2  s.  c  o  m
    /*      System.err.print("Message contents:");
          for (int i=0; i<msg.capacity(); i++)
             System.err.print(" "+Integer.toHexString(msg.get(i)).toUpperCase());
          System.err.println();
    */
    switch (type) {
    case HELLO: {
        // read the port information, and update the record for this place
        assert (datalen == 4 && source < numRequestedContainers.get() && source >= 0);
        final CommunicationLink linkInfo;
        LOG.info("Getting link for place " + source);
        synchronized (links) {
            linkInfo = links.get(source);
        }
        linkInfo.port = ((msg.get() & 0xFF) << 8) | (msg.get() & 0xFF); // unsigned short in network order
        linkInfo.sc = sc;

        // check if there are pending port requests for this place
        if (linkInfo.pendingPortRequests != null) {
            // prepare response message
            String linkString = linkInfo.node.getHost() + ":" + linkInfo.port;
            byte[] linkBytes = linkString.getBytes(); // matches existing code.  TODO: switch to UTF8
            ByteBuffer response = ByteBuffer.allocateDirect(headerLength + linkBytes.length)
                    .order(ByteOrder.nativeOrder());
            response.putInt(CTRL_MSG_TYPE.PORT_RESPONSE.ordinal());
            response.putInt(-1);
            response.putInt(source);
            response.putInt(linkBytes.length);
            response.put(linkBytes);
            // send response to each waiting place
            for (int place : linkInfo.pendingPortRequests) {
                response.putInt(4, place); // set the destination to the requesting place
                response.rewind();
                // TODO: this code may get stuck here if the reciever isn't reading properly
                try {
                    while (response.hasRemaining())
                        links.get(place).sc.write(response);
                } catch (IOException e) {
                    LOG.warn("Unable to send out port response for place " + place + " to place " + source, e);
                }
            }
            linkInfo.pendingPortRequests = null;
        }
        LOG.info("HELLO from place " + source + " at port " + linkInfo.port);

        if (pendingKills != null && pendingKills.containsKey(source)) {
            int delay = pendingKills.remove(source);
            LOG.info("Scheduling a takedown of place " + source + " in " + delay + " seconds");
            placeKiller.schedule(new Runnable() {
                @Override
                public void run() {
                    LOG.info("KILLING CONTAINER FOR PLACE " + source);
                    nodeManager.stopContainerAsync(linkInfo.container, linkInfo.node);
                }
            }, delay, TimeUnit.SECONDS);
        }
    }
        break;
    case GOODBYE: {
        try {
            CommunicationLink link = links.get(source);
            assert (link.pendingPortRequests == null);
            sc.close();
            link.port = PORT_DEAD;
        } catch (IOException e) {
            LOG.warn("Error closing socket channel", e);
        }
        LOG.info("GOODBYE to place " + source);
    }
        break;
    case PORT_REQUEST: {
        LOG.info("Got PORT_REQUEST from place " + source + " for place " + destination);
        // check to see if we know the requested information
        CommunicationLink linkInfo = links.get(destination);
        if (linkInfo.port != PORT_UNKNOWN) {
            String linkString;
            if (linkInfo.port == PORT_DEAD)
                linkString = DEAD;
            else
                linkString = linkInfo.node.getHost() + ":" + linkInfo.port;
            LOG.info("Telling place " + source + " that place " + destination + " is at " + linkString);
            byte[] linkBytes = linkString.getBytes(); // matches existing code.  TODO: switch to UTF8
            ByteBuffer response = ByteBuffer.allocateDirect(headerLength + linkBytes.length)
                    .order(ByteOrder.nativeOrder());
            response.putInt(CTRL_MSG_TYPE.PORT_RESPONSE.ordinal());
            response.putInt(source);
            response.putInt(destination);
            response.putInt(linkBytes.length);
            response.put(linkBytes);
            response.rewind();
            // TODO: this code may get stuck here if the reciever isn't reading properly
            try {
                while (response.hasRemaining())
                    sc.write(response);
            } catch (IOException e) {
                LOG.warn("Unable to send out port response for place " + destination + " to place " + source,
                        e);
            }
        } else { // port is not known.  remember we have a place asking for it when it becomes available
            if (linkInfo.pendingPortRequests == null)
                linkInfo.pendingPortRequests = new ArrayList<Integer>(2);
            linkInfo.pendingPortRequests.add(source);
            LOG.info("Stashing PORT_REQUEST from place " + source + " for place " + destination
                    + " until the answer is known");
        }
    }
        break;
    case LAUNCH_REQUEST: {
        assert (datalen == 8);
        int numPlacesRequested = (int) msg.getLong();

        int oldvalue = numRequestedContainers.getAndAdd((int) numPlacesRequested);

        // Send request for containers to RM
        for (int i = 0; i < numPlacesRequested; i++) {
            Resource capability = Resource.newInstance(memoryPerPlaceInMb, coresPerPlace);
            ContainerRequest request = new ContainerRequest(capability, null, null, Priority.newInstance(0));
            LOG.info("Adding a new container request " + request.toString());
            resourceManager.addContainerRequest(request);
            pendingRequests.add(request);
        }

        LOG.info("Requested an increase of " + numPlacesRequested + " places on top of the previous " + oldvalue
                + " places");
        msg.rewind();
        msg.putInt(CTRL_MSG_TYPE.LAUNCH_RESPONSE.ordinal());
        msg.rewind();
        try {
            while (msg.hasRemaining())
                sc.write(msg);
        } catch (IOException e) {
            LOG.warn("Unable to send out launch response to place " + source, e);
        }
    }
        break;
    default:
        LOG.warn("unknown message type " + type);
    }
    LOG.info("Finished processing message of size " + (headerLength + datalen) + " from place " + source);
}

From source file:x10.x10rt.yarn.Client.java

License:Open Source License

public void run() throws IOException, YarnException {
    yarnClient.start();// w ww  . ja v a 2 s . co m
    YarnClusterMetrics clusterMetrics = yarnClient.getYarnClusterMetrics();

    // print out cluster information
    LOG.info("Got Cluster metric info from ASM, numNodeManagers=" + clusterMetrics.getNumNodeManagers());
    List<NodeReport> clusterNodeReports = yarnClient.getNodeReports(NodeState.RUNNING);
    LOG.info("Got Cluster node info from ASM");
    for (NodeReport node : clusterNodeReports) {
        LOG.info("Got node report from ASM for" + ", nodeId=" + node.getNodeId() + ", nodeAddress"
                + node.getHttpAddress() + ", nodeRackName" + node.getRackName() + ", nodeNumContainers"
                + node.getNumContainers());
    }
    QueueInfo queueInfo = yarnClient.getQueueInfo(this.amQueue);
    LOG.info("Queue info" + ", queueName=" + queueInfo.getQueueName() + ", queueCurrentCapacity="
            + queueInfo.getCurrentCapacity() + ", queueMaxCapacity=" + queueInfo.getMaximumCapacity()
            + ", queueApplicationCount=" + queueInfo.getApplications().size() + ", queueChildQueueCount="
            + queueInfo.getChildQueues().size());
    List<QueueUserACLInfo> listAclInfo = yarnClient.getQueueAclsInfo();
    for (QueueUserACLInfo aclInfo : listAclInfo) {
        for (QueueACL userAcl : aclInfo.getUserAcls()) {
            LOG.info("User ACL Info for Queue" + ", queueName=" + aclInfo.getQueueName() + ", userAcl="
                    + userAcl.name());
        }
    }

    // Get a new application id
    YarnClientApplication app = yarnClient.createApplication();
    GetNewApplicationResponse appResponse = app.getNewApplicationResponse();

    int maxMem = appResponse.getMaximumResourceCapability().getMemory();
    LOG.info("Max mem capabililty of resources in this cluster " + maxMem);

    int maxVCores = appResponse.getMaximumResourceCapability().getVirtualCores();
    LOG.info("Max virtual cores capabililty of resources in this cluster " + maxVCores);

    // set the application name
    ApplicationSubmissionContext appContext = app.getApplicationSubmissionContext();
    final ApplicationId appId = appContext.getApplicationId();
    appContext.setKeepContainersAcrossApplicationAttempts(false);
    appContext.setApplicationName(appName);

    Map<String, LocalResource> localResources = new HashMap<String, LocalResource>();
    LOG.info("Copy App Master jar from local filesystem and add to local environment");
    // Copy the application master jar to the filesystem
    // Create a local resource to point to the destination jar path
    FileSystem fs = FileSystem.get(conf);
    StringBuilder x10jars = new StringBuilder();

    boolean isNative = Boolean.getBoolean(ApplicationMaster.X10_YARN_NATIVE);
    String[] jarfiles = classPath.split(":");
    // upload jar files
    for (String jar : jarfiles) {
        if (jar.endsWith(".jar")) {
            String nopath = jar.substring(jar.lastIndexOf('/') + 1);
            LOG.info("Uploading " + nopath + " to " + fs.getUri());
            x10jars.append(addToLocalResources(fs, jar, nopath, appId.toString(), localResources, null));
            if (isNative) {
                // add the user's program.
                LOG.info("Uploading application " + appName + " to " + fs.getUri());
                x10jars.append(':');
                x10jars.append(addToLocalResources(fs, args[mainClassArg], appName, appId.toString(),
                        localResources, null));
                break; // no other jar files are needed beyond the one holding ApplicationMaster, which is the first one
            } else
                x10jars.append(':');
        }
    }

    StringBuilder uploadedFiles = new StringBuilder();

    // upload any files specified via -upload argument to the x10 script
    String upload = System.getProperty(ApplicationMaster.X10_YARNUPLOAD);
    if (upload != null) {
        String[] files = upload.split(",");
        for (String file : files) {
            String nopath = file.substring(file.lastIndexOf('/') + 1);
            LOG.info("Uploading file " + nopath + " to " + fs.getUri());
            uploadedFiles.append(addToLocalResources(fs, file, nopath, appId.toString(), localResources, null));
            uploadedFiles.append(',');
        }
    }

    LOG.info("Set the environment for the application master");
    Map<String, String> env = new HashMap<String, String>();
    //env.putAll(System.getenv()); // copy all environment variables from the client side to the application side
    // copy over existing environment variables
    for (String key : System.getenv().keySet()) {
        if (!key.startsWith("BASH_FUNC_") && !key.equals("LS_COLORS")) // skip some
            env.put(ApplicationMaster.X10YARNENV_ + key, System.getenv(key));
    }
    String places = System.getenv(ApplicationMaster.X10_NPLACES);
    env.put(ApplicationMaster.X10_NPLACES, (places == null) ? "1" : places);
    String cores = System.getenv(ApplicationMaster.X10_NTHREADS);
    env.put(ApplicationMaster.X10_NTHREADS, (cores == null) ? "0" : cores);
    env.put(ApplicationMaster.X10_HDFS_JARS, x10jars.toString());

    // At some point we should not be required to add
    // the hadoop specific classpaths to the env.
    // It should be provided out of the box.
    // For now setting all required classpaths including
    // the classpath to "." for the application jar
    StringBuilder classPathEnv = new StringBuilder(Environment.CLASSPATH.$$())
            .append(ApplicationConstants.CLASS_PATH_SEPARATOR).append("./*");
    for (String c : conf.getStrings(YarnConfiguration.YARN_APPLICATION_CLASSPATH,
            YarnConfiguration.DEFAULT_YARN_CROSS_PLATFORM_APPLICATION_CLASSPATH)) {
        classPathEnv.append(ApplicationConstants.CLASS_PATH_SEPARATOR);
        classPathEnv.append(c.trim());
    }
    env.put("CLASSPATH", classPathEnv.toString());

    LOG.info("Completed setting up the ApplicationManager environment " + env.toString());

    // Set the necessary command to execute the application master
    Vector<CharSequence> vargs = new Vector<CharSequence>(this.args.length + 30);
    // Set java executable command
    LOG.info("Setting up app master command");
    vargs.add(Environment.JAVA_HOME.$$() + "/bin/java");
    // Set Xmx based on am memory size
    vargs.add("-Xmx" + amMemory + "m");
    // propigate the native flag
    if (isNative)
        vargs.add("-DX10_YARN_NATIVE=true");
    if (upload != null)
        vargs.add("-D" + ApplicationMaster.X10_YARNUPLOAD + "=" + uploadedFiles.toString());

    vargs.add("-D" + ApplicationMaster.X10_YARN_MAIN + "=" + appName);
    vargs.add("-Dorg.apache.commons.logging.simplelog.showdatetime=true");
    // Set class name
    vargs.add(appMasterMainClass);

    // add java arguments
    for (int i = 0; i < mainClassArg; i++) {
        if (i != classPathArg) // skip the classpath, as it gets reworked
            vargs.add(args[i]);
    }
    // add our own main class wrapper
    if (!isNative)
        vargs.add(X10MainRunner.class.getName());
    // add remaining application command line arguments
    for (int i = mainClassArg; i < args.length; i++)
        vargs.add(args[i]);

    vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stdout");
    vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stderr");
    // Get final commmand
    StringBuilder command = new StringBuilder();
    for (CharSequence str : vargs) {
        command.append(str).append(" ");
    }
    LOG.info("Completed setting up app master command " + command.toString());
    List<String> commands = new ArrayList<String>();
    commands.add(command.toString());

    // Set up the container launch context for the application master
    ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, env, commands, null,
            null, null);
    // Set up resource type requirements
    // For now, both memory and vcores are supported, so we set memory and
    // vcores requirements
    Resource capability = Resource.newInstance(amMemory, amVCores);
    appContext.setResource(capability);

    appContext.setAMContainerSpec(amContainer);

    // kill the application if the user hits ctrl-c
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println();
            System.out.println("Exiting...");
            forceKillApplication(appId);
        }
    }));

    LOG.info("Submitting application to ASM");
    yarnClient.submitApplication(appContext);

    // Monitor the application
    monitorApplication(appId);

    // delete jar files uploaded earlier
    cleanupLocalResources(fs, appId.toString());
}