<ahref="http://maven.apache.org/"title="Built by Maven"class="poweredBy">
<imgalt="Built by Maven"src="./images/logos/maven-feather.png"/>
</a>
</div>
</div>
<divid="bodyColumn">
<divid="contentBox">
<!---
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. See accompanying LICENSE file.
-->
<h1>Hadoop: Writing YARN Applications</h1>
<ul>
<li><ahref="#Purpose">Purpose</a></li>
<li><ahref="#Concepts_and_Flow">Concepts and Flow</a></li>
<li><ahref="#Interfaces">Interfaces</a></li>
<li><ahref="#Writing_a_Simple_YARN_Application">Writing a Simple YARN Application</a>
<ul>
<li><ahref="#Writing_a_simple_Client">Writing a simple Client</a></li>
<li><ahref="#Writing_an_ApplicationMaster_.28AM.29">Writing an ApplicationMaster (AM)</a></li></ul></li>
<li><ahref="#FAQ">FAQ</a>
<ul>
<li><ahref="#How_can_I_distribute_my_application.E2.80.99s_jars_to_all_of_the_nodes_in_the_YARN_cluster_that_need_it.3F">How can I distribute my application’s jars to all of the nodes in the YARN cluster that need it?</a></li>
<li><ahref="#How_do_I_get_the_ApplicationMaster.E2.80.99s_ApplicationAttemptId.3F">How do I get the ApplicationMaster’s ApplicationAttemptId?</a></li>
<li><ahref="#Why_my_container_is_killed_by_the_NodeManager.3F">Why my container is killed by the NodeManager?</a></li>
<li><ahref="#How_do_I_include_native_libraries.3F">How do I include native libraries?</a></li></ul></li>
<p>This document describes, at a high-level, the way to implement new Applications for YARN.</p></section><section>
<h2><aname="Concepts_and_Flow"></a>Concepts and Flow</h2>
<p>The general concept is that an <i>application submission client</i> submits an <i>application</i> to the YARN <i>ResourceManager</i> (RM). This can be done through setting up a <code>YarnClient</code> object. After <code>YarnClient</code> is started, the client can then set up application context, prepare the very first container of the application that contains the <i>ApplicationMaster</i> (AM), and then submit the application. You need to provide information such as the details about the local files/jars that need to be available for your application to run, the actual command that needs to be executed (with the necessary command line arguments), any OS environment settings (optional), etc. Effectively, you need to describe the Unix process(es) that needs to be launched for your ApplicationMaster.</p>
<p>The YARN ResourceManager will then launch the ApplicationMaster (as specified) on an allocated container. The ApplicationMaster communicates with YARN cluster, and handles application execution. It performs operations in an asynchronous fashion. During application launch time, the main tasks of the ApplicationMaster are: a) communicating with the ResourceManager to negotiate and allocate resources for future containers, and b) after container allocation, communicating YARN <i>NodeManager</i>s (NMs) to launch application containers on them. Task a) can be performed asynchronously through an <code>AMRMClientAsync</code> object, with event handling methods specified in a <code>AMRMClientAsync.CallbackHandler</code> type of event handler. The event handler needs to be set to the client explicitly. Task b) can be performed by launching a runnable object that then launches containers when there are containers allocated. As part of launching this container, the AM has to specify the <code>ContainerLaunchContext</code> that has the launch information such as command line specification, environment, etc.</p>
<p>During the execution of an application, the ApplicationMaster communicates NodeManagers through <code>NMClientAsync</code> object. All container events are handled by <code>NMClientAsync.CallbackHandler</code>, associated with <code>NMClientAsync</code>. A typical callback handler handles client start, stop, status update and error. ApplicationMaster also reports execution progress to ResourceManager by handling the <code>getProgress()</code> method of <code>AMRMClientAsync.CallbackHandler</code>.</p>
<p>Other than asynchronous clients, there are synchronous versions for certain workflows (<code>AMRMClient</code> and <code>NMClient</code>). The asynchronous clients are recommended because of (subjectively) simpler usages, and this article will mainly cover the asynchronous clients. Please refer to <code>AMRMClient</code> and <code>NMClient</code> for more information on synchronous clients.</p></section><section>
<p>Launch containers. Communicate with NodeManagers by using <code>NMClientAsync</code> objects, handling container events by <code>NMClientAsync.CallbackHandler</code></p>
</li>
</ul>
<p><b>Note</b></p>
<ul>
<li>
<p>The three main protocols for YARN application (ApplicationClientProtocol, ApplicationMasterProtocol and ContainerManagementProtocol) are still preserved. The 3 clients wrap these 3 protocols to provide simpler programming model for YARN applications.</p>
</li>
<li>
<p>Under very rare circumstances, programmer may want to directly use the 3 protocols to implement an application. However, note that <i>such behaviors are no longer encouraged for general use cases</i>.</p>
</li>
</ul></section><section>
<h2><aname="Writing_a_Simple_YARN_Application"></a>Writing a Simple YARN Application</h2><section>
<h3><aname="Writing_a_simple_Client"></a>Writing a simple Client</h3>
<ul>
<li>
<p>The first step that a client needs to do is to initialize and start a YarnClient.</p>
<p>The response from the <code>YarnClientApplication</code> for a new application also contains information about the cluster such as the minimum/maximum resource capabilities of the cluster. This is required so that to ensure that you can correctly set the specifications of the container in which the ApplicationMaster would be launched. Please refer to <code>GetNewApplicationResponse</code> for more details.</p>
</li>
<li>
<p>The main crux of a client is to setup the <code>ApplicationSubmissionContext</code> which defines all the information needed by the RM to launch the AM. A client needs to set the following into the context:</p>
</li>
<li>
<p>Application info: id, name</p>
</li>
<li>
<p>Queue, priority info: Queue to which the application will be submitted, the priority to be assigned for the application.</p>
</li>
<li>
<p>User: The user submitting the application</p>
</li>
<li>
<p><code>ContainerLaunchContext</code>: The information defining the container in which the AM will be launched and run. The <code>ContainerLaunchContext</code>, as mentioned previously, defines all the required information needed to run the application such as the local <b>R</b>esources (binaries, jars, files etc.), <b>E</b>nvironment settings (CLASSPATH etc.), the <b>C</b>ommand to be executed and security <b>T</b>okens (<i>RECT</i>).</p>
<p>At this point, the RM will have accepted the application and in the background, will go through the process of allocating a container with the required specifications and then eventually setting up and launching the AM on the allocated container.</p>
</li>
<li>
<p>There are multiple ways a client can track progress of the actual task.</p>
</li>
</ul>
<blockquote>
<ul>
<li>It can communicate with the RM and request for a report of the application via the <code>getApplicationReport()</code> method of <code>YarnClient</code>.</li>
</ul>
</blockquote>
<divclass="source">
<divclass="source">
<pre>// Get application report for the appId we are interested in
<p>The ApplicationReport received from the RM consists of the following:</p>
<blockquote>
<ul>
<li>
<p><i>General application information</i>: Application id, queue to which the application was submitted, user who submitted the application and the start time for the application.</p>
</li>
<li>
<p><i>ApplicationMaster details</i>: the host on which the AM is running, the rpc port (if any) on which it is listening for requests from clients and a token that the client needs to communicate with the AM.</p>
</li>
<li>
<p><i>Application tracking information</i>: If the application supports some form of progress tracking, it can set a tracking url which is available via <code>ApplicationReport</code>’s <code>getTrackingUrl()</code> method that a client can look at to monitor progress.</p>
</li>
<li>
<p><i>Application status</i>: The state of the application as seen by the ResourceManager is available via <code>ApplicationReport#getYarnApplicationState</code>. If the <code>YarnApplicationState</code> is set to <code>FINISHED</code>, the client should refer to <code>ApplicationReport#getFinalApplicationStatus</code> to check for the actual success/failure of the application task itself. In case of failures, <code>ApplicationReport#getDiagnostics</code> may be useful to shed some more light on the failure.</p>
</li>
</ul>
</blockquote>
<ul>
<li>If the ApplicationMaster supports it, a client can directly query the AM itself for progress updates via the host:rpcport information obtained from the application report. It can also use the tracking url obtained from the report if available.</li>
</ul>
</blockquote>
<ul>
<li>In certain situations, if the application is taking too long or due to other factors, the client may wish to kill the application. <code>YarnClient</code> supports the <code>killApplication</code> call that allows a client to send a kill signal to the AM via the ResourceManager. An ApplicationMaster if so designed may also support an abort call via its rpc layer that a client may be able to leverage.
<divclass="source">
<divclass="source">
<pre> yarnClient.killApplication(appId);
</pre></div></div>
</li>
</ul></section><section>
<h3><aname="Writing_an_ApplicationMaster_.28AM.29"></a>Writing an ApplicationMaster (AM)</h3>
<ul>
<li>
<p>The AM is the actual owner of the job. It will be launched by the RM and via the client will be provided all the necessary information and resources about the job that it has been tasked with to oversee and complete.</p>
</li>
<li>
<p>As the AM is launched within a container that may (likely will) be sharing a physical host with other containers, given the multi-tenancy nature, amongst other issues, it cannot make any assumptions of things like pre-configured ports that it can listen on.</p>
</li>
<li>
<p>When the AM starts up, several parameters are made available to it via the environment. These include the <code>ContainerId</code> for the AM container, the application submission time and details about the NM (NodeManager) host running the ApplicationMaster. Ref <code>ApplicationConstants</code> for parameter names.</p>
</li>
<li>
<p>All interactions with the RM require an <code>ApplicationAttemptId</code> (there can be multiple attempts per application in case of failures). The <code>ApplicationAttemptId</code> can be obtained from the AM’s container id. There are helper APIs to convert the value obtained from the environment into objects.</p>
<li>After an AM has initialized itself completely, we can start the two clients: one to ResourceManager, and one to NodeManagers. We set them up with our customized event handler, and we will talk about those event handlers in detail later in this article.</li>
</ul>
<divclass="source">
<divclass="source">
<pre> AMRMClientAsync.CallbackHandler allocListener = new RMCallbackHandler();
nmClientAsync = new NMClientAsyncImpl(containerListener);
nmClientAsync.init(conf);
nmClientAsync.start();
</pre></div></div>
<ul>
<li>The AM has to emit heartbeats to the RM to keep it informed that the AM is alive and still running. The timeout expiry interval at the RM is defined by a config setting accessible via <code>YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS</code> with the default being defined by <code>YarnConfiguration.DEFAULT_RM_AM_EXPIRY_INTERVAL_MS</code>. The ApplicationMaster needs to register itself with the ResourceManager to start heartbeating.</li>
<li>In the response of the registration, maximum resource capability if included. You may want to use this to check the application’s request.</li>
</ul>
<divclass="source">
<divclass="source">
<pre>// Dump out information about cluster capability as seen by the
// resource manager
int maxMem = response.getMaximumResourceCapability().getMemory();
LOG.info("Max mem capability of resources in this cluster " + maxMem);
int maxVCores = response.getMaximumResourceCapability().getVirtualCores();
LOG.info("Max vcores capability of resources in this cluster " + maxVCores);
// A resource ask cannot exceed the max.
if (containerMemory > maxMem) {
LOG.info("Container memory specified above max threshold of cluster."
+ " Using max value." + ", specified=" + containerMemory + ", max="
+ maxMem);
containerMemory = maxMem;
}
if (containerVirtualCores > maxVCores) {
LOG.info("Container virtual cores specified above max threshold of cluster."
+ " Using max value." + ", specified=" + containerVirtualCores + ", max="
+ " previous AM's running containers on AM registration.");
</pre></div></div>
<ul>
<li>Based on the task requirements, the AM can ask for a set of containers to run its tasks on. We can now calculate how many containers we need, and request those many containers.</li>
<li>In <code>setupContainerAskForRM()</code>, the follow two things need some set up:</li>
</ul>
<blockquote>
<ul>
<li>
<p>Resource capability: Currently, YARN supports memory based resource requirements so the request should define how much memory is needed. The value is defined in MB and has to less than the max capability of the cluster and an exact multiple of the min capability. Memory resources correspond to physical memory limits imposed on the task containers. It will also support computation based resource (vCore), as shown in the code.</p>
</li>
<li>
<p>Priority: When asking for sets of containers, an AM may define different priorities to each set. For example, the Map-Reduce AM may assign a higher priority to containers needed for the Map tasks and a lower priority for the Reduce tasks’ containers.</p>
<li>After container allocation requests have been sent by the application manager, containers will be launched asynchronously, by the event handler of the <code>AMRMClientAsync</code> client. The handler should implement <code>AMRMClientAsync.CallbackHandler</code> interface.</li>
</ul>
<blockquote>
<ul>
<li>When there are containers allocated, the handler sets up a thread that runs the code to launch containers. Here we use the name <code>LaunchContainerRunnable</code> to demonstrate. We will talk about the <code>LaunchContainerRunnable</code> class in the following part of this article.</li>
</ul>
</blockquote>
<divclass="source">
<divclass="source">
<pre>@Override
public void onContainersAllocated(List<Container> allocatedContainers) {
LOG.info("Got response from RM for container ask, allocatedCnt="
<li>The container launch thread actually launches the containers on NMs. After a container has been allocated to the AM, it needs to follow a similar process that the client followed in setting up the <code>ContainerLaunchContext</code> for the eventual task that is going to be running on the allocated Container. Once the <code>ContainerLaunchContext</code> is defined, the AM can start it through the <code>NMClientAsync</code>.</li>
</ul>
<divclass="source">
<divclass="source">
<pre>// Set the necessary command to execute on the allocated container
Vector<CharSequence> vargs = new Vector<CharSequence>(5);
<p>The <code>NMClientAsync</code> object, together with its event handler, handles container events. Including container start, stop, status update, and occurs an error.</p>
</li>
<li>
<p>After the ApplicationMaster determines the work is done, it needs to unregister itself through the AM-RM client, and then stops the client.</p>
LOG.error("Failed to unregister application", ex);
} catch (IOException e) {
LOG.error("Failed to unregister application", e);
}
amRMClient.stop();
</pre></div></div>
</section></section><section>
<h2><aname="FAQ"></a>FAQ</h2><section>
<h3><aname="How_can_I_distribute_my_application.E2.80.99s_jars_to_all_of_the_nodes_in_the_YARN_cluster_that_need_it.3F"></a>How can I distribute my application’s jars to all of the nodes in the YARN cluster that need it?</h3>
<p>You can use the LocalResource to add resources to your application request. This will cause YARN to distribute the resource to the ApplicationMaster node. If the resource is a tgz, zip, or jar - you can have YARN unzip it. Then, all you need to do is add the unzipped folder to your classpath. For example, when creating your application request:</p>
<p>As you can see, the <code>setLocalResources</code> command takes a map of names to resources. The name becomes a sym link in your application’s cwd, so you can just refer to the artifacts inside by using ./package/*.</p>
<p><b>Note</b>: Java’s classpath (cp) argument is VERY sensitive. Make sure you get the syntax EXACTLY correct.</p>
<p>Once your package is distributed to your AM, you’ll need to follow the same process whenever your AM starts a new container (assuming you want the resources to be sent to your container). The code for this is the same. You just need to make sure that you give your AM the package path (either HDFS, or local), so that it can send the resource URL along with the container ctx.</p></section><section>
<h3><aname="How_do_I_get_the_ApplicationMaster.E2.80.99s_ApplicationAttemptId.3F"></a>How do I get the ApplicationMaster’s <code>ApplicationAttemptId</code>?</h3>
<p>The <code>ApplicationAttemptId</code> will be passed to the AM via the environment and the value from the environment can be converted into an <code>ApplicationAttemptId</code> object via the ConverterUtils helper function.</p></section><section>
<h3><aname="Why_my_container_is_killed_by_the_NodeManager.3F"></a>Why my container is killed by the NodeManager?</h3>
<p>This is likely due to high memory usage exceeding your requested container memory size. There are a number of reasons that can cause this. First, look at the process tree that the NodeManager dumps when it kills your container. The two things you’re interested in are physical memory and virtual memory. If you have exceeded physical memory limits your app is using too much physical memory. If you’re running a Java app, you can use -hprof to look at what is taking up space in the heap. If you have exceeded virtual memory, you may need to increase the value of the cluster-wide configuration variable <code>yarn.nodemanager.vmem-pmem-ratio</code>.</p></section><section>
<h3><aname="How_do_I_include_native_libraries.3F"></a>How do I include native libraries?</h3>
<p>Setting <code>-Djava.library.path</code> on the command line while launching a container can cause native libraries used by Hadoop to not be loaded correctly and can result in errors. It is cleaner to use <code>LD_LIBRARY_PATH</code> instead.</p></section></section><section>
<p>YARN distributed shell: in <code>hadoop-yarn-applications-distributedshell</code> project after you set up your development environment.</p></section>