hadoop/hadoop-yarn/hadoop-yarn-site/WritingYarnApplications.html

1248 lines
60 KiB
HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
| Generated by Apache Maven Doxia at 2023-05-23
| Rendered using Apache Maven Stylus Skin 1.5
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Apache Hadoop 3.4.0-SNAPSHOT &#x2013; Hadoop: Writing YARN Applications</title>
<style type="text/css" media="all">
@import url("./css/maven-base.css");
@import url("./css/maven-theme.css");
@import url("./css/site.css");
</style>
<link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
<meta name="Date-Revision-yyyymmdd" content="20230523" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body class="composite">
<div id="banner">
<a href="http://hadoop.apache.org/" id="bannerLeft">
<img src="http://hadoop.apache.org/images/hadoop-logo.jpg" alt="" />
</a>
<a href="http://www.apache.org/" id="bannerRight">
<img src="http://www.apache.org/images/asf_logo_wide.png" alt="" />
</a>
<div class="clear">
<hr/>
</div>
</div>
<div id="breadcrumbs">
<div class="xright"> <a href="http://wiki.apache.org/hadoop" class="externalLink">Wiki</a>
|
<a href="https://gitbox.apache.org/repos/asf/hadoop.git" class="externalLink">git</a>
|
<a href="http://hadoop.apache.org/" class="externalLink">Apache Hadoop</a>
&nbsp;| Last Published: 2023-05-23
&nbsp;| Version: 3.4.0-SNAPSHOT
</div>
<div class="clear">
<hr/>
</div>
</div>
<div id="leftColumn">
<div id="navcolumn">
<h5>General</h5>
<ul>
<li class="none">
<a href="../../index.html">Overview</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/SingleCluster.html">Single Node Setup</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/ClusterSetup.html">Cluster Setup</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/CommandsManual.html">Commands Reference</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/FileSystemShell.html">FileSystem Shell</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/Compatibility.html">Compatibility Specification</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/DownstreamDev.html">Downstream Developer's Guide</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/AdminCompatibilityGuide.html">Admin Compatibility Guide</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/InterfaceClassification.html">Interface Classification</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/filesystem/index.html">FileSystem Specification</a>
</li>
</ul>
<h5>Common</h5>
<ul>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/CLIMiniCluster.html">CLI Mini Cluster</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/FairCallQueue.html">Fair Call Queue</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/NativeLibraries.html">Native Libraries</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/Superusers.html">Proxy User</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/RackAwareness.html">Rack Awareness</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/SecureMode.html">Secure Mode</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/ServiceLevelAuth.html">Service Level Authorization</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/HttpAuthentication.html">HTTP Authentication</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/CredentialProviderAPI.html">Credential Provider API</a>
</li>
<li class="none">
<a href="../../hadoop-kms/index.html">Hadoop KMS</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/Tracing.html">Tracing</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/UnixShellGuide.html">Unix Shell Guide</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/registry/index.html">Registry</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/AsyncProfilerServlet.html">Async Profiler</a>
</li>
</ul>
<h5>HDFS</h5>
<ul>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsDesign.html">Architecture</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsUserGuide.html">User Guide</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HDFSCommands.html">Commands Reference</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HDFSHighAvailabilityWithQJM.html">NameNode HA With QJM</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HDFSHighAvailabilityWithNFS.html">NameNode HA With NFS</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/ObserverNameNode.html">Observer NameNode</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/Federation.html">Federation</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/ViewFs.html">ViewFs</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/ViewFsOverloadScheme.html">ViewFsOverloadScheme</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsSnapshots.html">Snapshots</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsEditsViewer.html">Edits Viewer</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsImageViewer.html">Image Viewer</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsPermissionsGuide.html">Permissions and HDFS</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsQuotaAdminGuide.html">Quotas and HDFS</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/LibHdfs.html">libhdfs (C API)</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/WebHDFS.html">WebHDFS (REST API)</a>
</li>
<li class="none">
<a href="../../hadoop-hdfs-httpfs/index.html">HttpFS</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/ShortCircuitLocalReads.html">Short Circuit Local Reads</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/CentralizedCacheManagement.html">Centralized Cache Management</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsNfsGateway.html">NFS Gateway</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsRollingUpgrade.html">Rolling Upgrade</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/ExtendedAttributes.html">Extended Attributes</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/TransparentEncryption.html">Transparent Encryption</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsMultihoming.html">Multihoming</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/ArchivalStorage.html">Storage Policies</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/MemoryStorage.html">Memory Storage Support</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/SLGUserGuide.html">Synthetic Load Generator</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HDFSErasureCoding.html">Erasure Coding</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HDFSDiskbalancer.html">Disk Balancer</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsUpgradeDomain.html">Upgrade Domain</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsDataNodeAdminGuide.html">DataNode Admin</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs-rbf/HDFSRouterFederation.html">Router Federation</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/HdfsProvidedStorage.html">Provided Storage</a>
</li>
</ul>
<h5>MapReduce</h5>
<ul>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html">Tutorial</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapredCommands.html">Commands Reference</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduce_Compatibility_Hadoop1_Hadoop2.html">Compatibility with 1.x</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/EncryptedShuffle.html">Encrypted Shuffle</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/PluggableShuffleAndPluggableSort.html">Pluggable Shuffle/Sort</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/DistributedCacheDeploy.html">Distributed Cache Deploy</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/SharedCacheSupport.html">Support for YARN Shared Cache</a>
</li>
</ul>
<h5>MapReduce REST APIs</h5>
<ul>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapredAppMasterRest.html">MR Application Master</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-hs/HistoryServerRest.html">MR History Server</a>
</li>
</ul>
<h5>YARN</h5>
<ul>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/YARN.html">Architecture</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/YarnCommands.html">Commands Reference</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/CapacityScheduler.html">Capacity Scheduler</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/FairScheduler.html">Fair Scheduler</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/ResourceManagerRestart.html">ResourceManager Restart</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/ResourceManagerHA.html">ResourceManager HA</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/ResourceModel.html">Resource Model</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/NodeLabel.html">Node Labels</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/NodeAttributes.html">Node Attributes</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/WebApplicationProxy.html">Web Application Proxy</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/TimelineServer.html">Timeline Server</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/TimelineServiceV2.html">Timeline Service V.2</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/WritingYarnApplications.html">Writing YARN Applications</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/YarnApplicationSecurity.html">YARN Application Security</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/NodeManager.html">NodeManager</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/DockerContainers.html">Running Applications in Docker Containers</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/RuncContainers.html">Running Applications in runC Containers</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/NodeManagerCgroups.html">Using CGroups</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/SecureContainer.html">Secure Containers</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/ReservationSystem.html">Reservation System</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/GracefulDecommission.html">Graceful Decommission</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/OpportunisticContainers.html">Opportunistic Containers</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/Federation.html">YARN Federation</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/SharedCache.html">Shared Cache</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/UsingGpus.html">Using GPU</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/UsingFPGA.html">Using FPGA</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/PlacementConstraints.html">Placement Constraints</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/YarnUI2.html">YARN UI2</a>
</li>
</ul>
<h5>YARN REST APIs</h5>
<ul>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/WebServicesIntro.html">Introduction</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/ResourceManagerRest.html">Resource Manager</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/NodeManagerRest.html">Node Manager</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/TimelineServer.html#Timeline_Server_REST_API_v1">Timeline Server</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/TimelineServiceV2.html#Timeline_Service_v.2_REST_API">Timeline Service V.2</a>
</li>
</ul>
<h5>YARN Service</h5>
<ul>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/yarn-service/Overview.html">Overview</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/yarn-service/QuickStart.html">QuickStart</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/yarn-service/Concepts.html">Concepts</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/yarn-service/YarnServiceAPI.html">Yarn Service API</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/yarn-service/ServiceDiscovery.html">Service Discovery</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-site/yarn-service/SystemServices.html">System Services</a>
</li>
</ul>
<h5>Hadoop Compatible File Systems</h5>
<ul>
<li class="none">
<a href="../../hadoop-aliyun/tools/hadoop-aliyun/index.html">Aliyun OSS</a>
</li>
<li class="none">
<a href="../../hadoop-aws/tools/hadoop-aws/index.html">Amazon S3</a>
</li>
<li class="none">
<a href="../../hadoop-azure/index.html">Azure Blob Storage</a>
</li>
<li class="none">
<a href="../../hadoop-azure-datalake/index.html">Azure Data Lake Storage</a>
</li>
<li class="none">
<a href="../../hadoop-cos/cloud-storage/index.html">Tencent COS</a>
</li>
<li class="none">
<a href="../../hadoop-huaweicloud/cloud-storage/index.html">Huaweicloud OBS</a>
</li>
</ul>
<h5>Auth</h5>
<ul>
<li class="none">
<a href="../../hadoop-auth/index.html">Overview</a>
</li>
<li class="none">
<a href="../../hadoop-auth/Examples.html">Examples</a>
</li>
<li class="none">
<a href="../../hadoop-auth/Configuration.html">Configuration</a>
</li>
<li class="none">
<a href="../../hadoop-auth/BuildingIt.html">Building</a>
</li>
</ul>
<h5>Tools</h5>
<ul>
<li class="none">
<a href="../../hadoop-streaming/HadoopStreaming.html">Hadoop Streaming</a>
</li>
<li class="none">
<a href="../../hadoop-archives/HadoopArchives.html">Hadoop Archives</a>
</li>
<li class="none">
<a href="../../hadoop-archive-logs/HadoopArchiveLogs.html">Hadoop Archive Logs</a>
</li>
<li class="none">
<a href="../../hadoop-distcp/DistCp.html">DistCp</a>
</li>
<li class="none">
<a href="../../hadoop-federation-balance/HDFSFederationBalance.html">HDFS Federation Balance</a>
</li>
<li class="none">
<a href="../../hadoop-gridmix/GridMix.html">GridMix</a>
</li>
<li class="none">
<a href="../../hadoop-rumen/Rumen.html">Rumen</a>
</li>
<li class="none">
<a href="../../hadoop-resourceestimator/ResourceEstimator.html">Resource Estimator Service</a>
</li>
<li class="none">
<a href="../../hadoop-sls/SchedulerLoadSimulator.html">Scheduler Load Simulator</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/Benchmarking.html">Hadoop Benchmarking</a>
</li>
<li class="none">
<a href="../../hadoop-dynamometer/Dynamometer.html">Dynamometer</a>
</li>
</ul>
<h5>Reference</h5>
<ul>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/release/">Changelog and Release Notes</a>
</li>
<li class="none">
<a href="../../api/index.html">Java API docs</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/UnixShellAPI.html">Unix Shell API</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/Metrics.html">Metrics</a>
</li>
</ul>
<h5>Configuration</h5>
<ul>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/core-default.xml">core-default.xml</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs/hdfs-default.xml">hdfs-default.xml</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-hdfs-rbf/hdfs-rbf-default.xml">hdfs-rbf-default.xml</a>
</li>
<li class="none">
<a href="../../hadoop-mapreduce-client/hadoop-mapreduce-client-core/mapred-default.xml">mapred-default.xml</a>
</li>
<li class="none">
<a href="../../hadoop-yarn/hadoop-yarn-common/yarn-default.xml">yarn-default.xml</a>
</li>
<li class="none">
<a href="../../hadoop-kms/kms-default.html">kms-default.xml</a>
</li>
<li class="none">
<a href="../../hadoop-hdfs-httpfs/httpfs-default.html">httpfs-default.xml</a>
</li>
<li class="none">
<a href="../../hadoop-project-dist/hadoop-common/DeprecatedProperties.html">Deprecated Properties</a>
</li>
</ul>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img alt="Built by Maven" src="./images/logos/maven-feather.png"/>
</a>
</div>
</div>
<div id="bodyColumn">
<div id="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><a href="#Purpose">Purpose</a></li>
<li><a href="#Concepts_and_Flow">Concepts and Flow</a></li>
<li><a href="#Interfaces">Interfaces</a></li>
<li><a href="#Writing_a_Simple_YARN_Application">Writing a Simple YARN Application</a>
<ul>
<li><a href="#Writing_a_simple_Client">Writing a simple Client</a></li>
<li><a href="#Writing_an_ApplicationMaster_.28AM.29">Writing an ApplicationMaster (AM)</a></li></ul></li>
<li><a href="#FAQ">FAQ</a>
<ul>
<li><a href="#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&#x2019;s jars to all of the nodes in the YARN cluster that need it?</a></li>
<li><a href="#How_do_I_get_the_ApplicationMaster.E2.80.99s_ApplicationAttemptId.3F">How do I get the ApplicationMaster&#x2019;s ApplicationAttemptId?</a></li>
<li><a href="#Why_my_container_is_killed_by_the_NodeManager.3F">Why my container is killed by the NodeManager?</a></li>
<li><a href="#How_do_I_include_native_libraries.3F">How do I include native libraries?</a></li></ul></li>
<li><a href="#Useful_Links">Useful Links</a></li>
<li><a href="#Sample_Code">Sample Code</a></li></ul>
<section>
<h2><a name="Purpose"></a>Purpose</h2>
<p>This document describes, at a high-level, the way to implement new Applications for YARN.</p></section><section>
<h2><a name="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>
<h2><a name="Interfaces"></a>Interfaces</h2>
<p>Following are the important interfaces:</p>
<ul>
<li>
<p><b>Client</b>&lt;--&gt;<b>ResourceManager</b></p>
<p>By using <code>YarnClient</code> objects.</p>
</li>
<li>
<p><b>ApplicationMaster</b>&lt;--&gt;<b>ResourceManager</b></p>
<p>By using <code>AMRMClientAsync</code> objects, handling events asynchronously by <code>AMRMClientAsync.CallbackHandler</code></p>
</li>
<li>
<p><b>ApplicationMaster</b>&lt;--&gt;<b>NodeManager</b></p>
<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><a name="Writing_a_Simple_YARN_Application"></a>Writing a Simple YARN Application</h2><section>
<h3><a name="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>
<div class="source">
<div class="source">
<pre> YarnClient yarnClient = YarnClient.createYarnClient();
yarnClient.init(conf);
yarnClient.start();
</pre></div></div>
</li>
<li>
<p>Once a client is set up, the client needs to create an application, and get its application id.</p>
<div class="source">
<div class="source">
<pre> YarnClientApplication app = yarnClient.createApplication();
GetNewApplicationResponse appResponse = app.getNewApplicationResponse();
</pre></div></div>
</li>
<li>
<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>
</li>
</ul>
<div class="source">
<div class="source">
<pre>// set the application submission context
ApplicationSubmissionContext appContext = app.getApplicationSubmissionContext();
ApplicationId appId = appContext.getApplicationId();
appContext.setKeepContainersAcrossApplicationAttempts(keepContainers);
appContext.setApplicationName(appName);
// set local resources for the application master
// local files or archives as needed
// In this scenario, the jar file for the application master is part of the local resources
Map&lt;String, LocalResource&gt; localResources = new HashMap&lt;String, LocalResource&gt;();
LOG.info(&quot;Copy App Master jar from local filesystem and add to local environment&quot;);
// Copy the application master jar to the filesystem
// Create a local resource to point to the destination jar path
FileSystem fs = FileSystem.get(conf);
addToLocalResources(fs, appMasterJar, appMasterJarPath, appId.toString(),
localResources, null);
// Set the log4j properties if needed
if (!log4jPropFile.isEmpty()) {
addToLocalResources(fs, log4jPropFile, log4jPath, appId.toString(),
localResources, null);
}
// The shell script has to be made available on the final container(s)
// where it will be executed.
// To do this, we need to first copy into the filesystem that is visible
// to the yarn framework.
// We do not need to set this as a local resource for the application
// master as the application master does not need it.
String hdfsShellScriptLocation = &quot;&quot;;
long hdfsShellScriptLen = 0;
long hdfsShellScriptTimestamp = 0;
if (!shellScriptPath.isEmpty()) {
Path shellSrc = new Path(shellScriptPath);
String shellPathSuffix =
appName + &quot;/&quot; + appId.toString() + &quot;/&quot; + SCRIPT_PATH;
Path shellDst =
new Path(fs.getHomeDirectory(), shellPathSuffix);
fs.copyFromLocalFile(false, true, shellSrc, shellDst);
hdfsShellScriptLocation = shellDst.toUri().toString();
FileStatus shellFileStatus = fs.getFileStatus(shellDst);
hdfsShellScriptLen = shellFileStatus.getLen();
hdfsShellScriptTimestamp = shellFileStatus.getModificationTime();
}
if (!shellCommand.isEmpty()) {
addToLocalResources(fs, null, shellCommandPath, appId.toString(),
localResources, shellCommand);
}
if (shellArgs.length &gt; 0) {
addToLocalResources(fs, null, shellArgsPath, appId.toString(),
localResources, StringUtils.join(shellArgs, &quot; &quot;));
}
// Set the env variables to be setup in the env where the application master will be run
LOG.info(&quot;Set the environment for the application master&quot;);
Map&lt;String, String&gt; env = new HashMap&lt;String, String&gt;();
// put location of shell script into env
// using the env info, the application master will create the correct local resource for the
// eventual containers that will be launched to execute the shell scripts
env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTLOCATION, hdfsShellScriptLocation);
env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTTIMESTAMP, Long.toString(hdfsShellScriptTimestamp));
env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTLEN, Long.toString(hdfsShellScriptLen));
// Add AppMaster.jar location to classpath
// 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 &quot;.&quot; for the application jar
StringBuilder classPathEnv = new StringBuilder(Environment.CLASSPATH.$$())
.append(ApplicationConstants.CLASS_PATH_SEPARATOR).append(&quot;./*&quot;);
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());
}
classPathEnv.append(ApplicationConstants.CLASS_PATH_SEPARATOR).append(
&quot;./log4j.properties&quot;);
// Set the necessary command to execute the application master
Vector&lt;CharSequence&gt; vargs = new Vector&lt;CharSequence&gt;(30);
// Set java executable command
LOG.info(&quot;Setting up app master command&quot;);
vargs.add(Environment.JAVA_HOME.$$() + &quot;/bin/java&quot;);
// Set Xmx based on am memory size
vargs.add(&quot;-Xmx&quot; + amMemory + &quot;m&quot;);
// Set class name
vargs.add(appMasterMainClass);
// Set params for Application Master
vargs.add(&quot;--container_memory &quot; + String.valueOf(containerMemory));
vargs.add(&quot;--container_vcores &quot; + String.valueOf(containerVirtualCores));
vargs.add(&quot;--num_containers &quot; + String.valueOf(numContainers));
vargs.add(&quot;--priority &quot; + String.valueOf(shellCmdPriority));
for (Map.Entry&lt;String, String&gt; entry : shellEnv.entrySet()) {
vargs.add(&quot;--shell_env &quot; + entry.getKey() + &quot;=&quot; + entry.getValue());
}
if (debugFlag) {
vargs.add(&quot;--debug&quot;);
}
vargs.add(&quot;1&gt;&quot; + ApplicationConstants.LOG_DIR_EXPANSION_VAR + &quot;/AppMaster.stdout&quot;);
vargs.add(&quot;2&gt;&quot; + ApplicationConstants.LOG_DIR_EXPANSION_VAR + &quot;/AppMaster.stderr&quot;);
// Get final command
StringBuilder command = new StringBuilder();
for (CharSequence str : vargs) {
command.append(str).append(&quot; &quot;);
}
LOG.info(&quot;Completed setting up app master command &quot; + command.toString());
List&lt;String&gt; commands = new ArrayList&lt;String&gt;();
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);
// Service data is a binary blob that can be passed to the application
// Not needed in this scenario
// amContainer.setServiceData(serviceData);
// Setup security tokens
if (UserGroupInformation.isSecurityEnabled()) {
// Note: Credentials class is marked as LimitedPrivate for HDFS and MapReduce
Credentials credentials = new Credentials();
String tokenRenewer = conf.get(YarnConfiguration.RM_PRINCIPAL);
if (tokenRenewer == null | | tokenRenewer.length() == 0) {
throw new IOException(
&quot;Can't get Master Kerberos principal for the RM to use as renewer&quot;);
}
// For now, only getting tokens for the default file-system.
final Token&lt;?&gt; tokens[] =
fs.addDelegationTokens(tokenRenewer, credentials);
if (tokens != null) {
for (Token&lt;?&gt; token : tokens) {
LOG.info(&quot;Got dt for &quot; + fs.getUri() + &quot;; &quot; + token);
}
}
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
ByteBuffer fsTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
amContainer.setTokens(fsTokens);
}
appContext.setAMContainerSpec(amContainer);
</pre></div></div>
<ul>
<li>After the setup process is complete, the client is ready to submit the application with specified priority and queue.</li>
</ul>
<div class="source">
<div class="source">
<pre>// Set the priority for the application master
Priority pri = Priority.newInstance(amPriority);
appContext.setPriority(pri);
// Set the queue to which this application is to be submitted in the RM
appContext.setQueue(amQueue);
// Submit the application to the applications manager
// SubmitApplicationResponse submitResp = applicationsManager.submitApplication(appRequest);
yarnClient.submitApplication(appContext);
</pre></div></div>
<ul>
<li>
<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>
<div class="source">
<div class="source">
<pre>// Get application report for the appId we are interested in
ApplicationReport report = yarnClient.getApplicationReport(appId);
</pre></div></div>
<blockquote>
<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>&#x2019;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.
<div class="source">
<div class="source">
<pre> yarnClient.killApplication(appId);
</pre></div></div>
</li>
</ul></section><section>
<h3><a name="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&#x2019;s container id. There are helper APIs to convert the value obtained from the environment into objects.</p>
</li>
</ul>
<div class="source">
<div class="source">
<pre>Map&lt;String, String&gt; envs = System.getenv();
String containerIdString =
envs.get(ApplicationConstants.AM_CONTAINER_ID_ENV);
if (containerIdString == null) {
// container id should always be set in the env by the framework
throw new IllegalArgumentException(
&quot;ContainerId not set in the environment&quot;);
}
ContainerId containerId = ConverterUtils.toContainerId(containerIdString);
ApplicationAttemptId appAttemptID = containerId.getApplicationAttemptId();
</pre></div></div>
<ul>
<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>
<div class="source">
<div class="source">
<pre> AMRMClientAsync.CallbackHandler allocListener = new RMCallbackHandler();
amRMClient = AMRMClientAsync.createAMRMClientAsync(1000, allocListener);
amRMClient.init(conf);
amRMClient.start();
containerListener = createNMCallbackHandler();
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>
</ul>
<div class="source">
<div class="source">
<pre>// Register self with ResourceManager
// This will start heartbeating to the RM
appMasterHostname = NetUtils.getHostname();
RegisterApplicationMasterResponse response = amRMClient
.registerApplicationMaster(appMasterHostname, appMasterRpcPort,
appMasterTrackingUrl);
</pre></div></div>
<ul>
<li>In the response of the registration, maximum resource capability if included. You may want to use this to check the application&#x2019;s request.</li>
</ul>
<div class="source">
<div class="source">
<pre>// Dump out information about cluster capability as seen by the
// resource manager
int maxMem = response.getMaximumResourceCapability().getMemory();
LOG.info(&quot;Max mem capability of resources in this cluster &quot; + maxMem);
int maxVCores = response.getMaximumResourceCapability().getVirtualCores();
LOG.info(&quot;Max vcores capability of resources in this cluster &quot; + maxVCores);
// A resource ask cannot exceed the max.
if (containerMemory &gt; maxMem) {
LOG.info(&quot;Container memory specified above max threshold of cluster.&quot;
+ &quot; Using max value.&quot; + &quot;, specified=&quot; + containerMemory + &quot;, max=&quot;
+ maxMem);
containerMemory = maxMem;
}
if (containerVirtualCores &gt; maxVCores) {
LOG.info(&quot;Container virtual cores specified above max threshold of cluster.&quot;
+ &quot; Using max value.&quot; + &quot;, specified=&quot; + containerVirtualCores + &quot;, max=&quot;
+ maxVCores);
containerVirtualCores = maxVCores;
}
List&lt;Container&gt; previousAMRunningContainers =
response.getContainersFromPreviousAttempts();
LOG.info(&quot;Received &quot; + previousAMRunningContainers.size()
+ &quot; previous AM's running containers on AM registration.&quot;);
</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>
</ul>
<div class="source">
<div class="source">
<pre>List&lt;Container&gt; previousAMRunningContainers =
response.getContainersFromPreviousAttempts();
LOG.info(&quot;Received &quot; + previousAMRunningContainers.size()
+ &quot; previous AM's running containers on AM registration.&quot;);
int numTotalContainersToRequest =
numTotalContainers - previousAMRunningContainers.size();
// Setup ask for containers from RM
// Send request for containers to RM
// Until we get our fully allocated quota, we keep on polling RM for
// containers
// Keep looping until all the containers are launched and shell script
// executed on them ( regardless of success/failure).
for (int i = 0; i &lt; numTotalContainersToRequest; ++i) {
ContainerRequest containerAsk = setupContainerAskForRM();
amRMClient.addContainerRequest(containerAsk);
}
</pre></div></div>
<ul>
<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&#x2019; containers.</p>
</li>
</ul>
</blockquote>
<div class="source">
<div class="source">
<pre>private ContainerRequest setupContainerAskForRM() {
// setup requirements for hosts
// using * as any host will do for the distributed shell app
// set the priority for the request
Priority pri = Priority.newInstance(requestPriority);
// Set up resource type requirements
// For now, memory and CPU are supported so we set memory and cpu requirements
Resource capability = Resource.newInstance(containerMemory,
containerVirtualCores);
ContainerRequest request = new ContainerRequest(capability, null, null,
pri);
LOG.info(&quot;Requested container ask: &quot; + request.toString());
return request;
}
</pre></div></div>
<ul>
<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>
<div class="source">
<div class="source">
<pre>@Override
public void onContainersAllocated(List&lt;Container&gt; allocatedContainers) {
LOG.info(&quot;Got response from RM for container ask, allocatedCnt=&quot;
+ allocatedContainers.size());
numAllocatedContainers.addAndGet(allocatedContainers.size());
for (Container allocatedContainer : allocatedContainers) {
LaunchContainerRunnable runnableLaunchContainer =
new LaunchContainerRunnable(allocatedContainer, containerListener);
Thread launchThread = new Thread(runnableLaunchContainer);
// launch and start the container on a separate thread to keep
// the main thread unblocked
// as all containers may not be allocated at one go.
launchThreads.add(launchThread);
launchThread.start();
}
}
</pre></div></div>
<blockquote>
<ul>
<li>On heart beat, the event handler reports the progress of the application.</li>
</ul>
</blockquote>
<div class="source">
<div class="source">
<pre>@Override
public float getProgress() {
// set progress to deliver to RM on next heartbeat
float progress = (float) numCompletedContainers.get()
/ numTotalContainers;
return progress;
}
</pre></div></div>
<ul>
<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>
<div class="source">
<div class="source">
<pre>// Set the necessary command to execute on the allocated container
Vector&lt;CharSequence&gt; vargs = new Vector&lt;CharSequence&gt;(5);
// Set executable command
vargs.add(shellCommand);
// Set shell script path
if (!scriptPath.isEmpty()) {
vargs.add(Shell.WINDOWS ? ExecBatScripStringtPath
: ExecShellStringPath);
}
// Set args for the shell command if any
vargs.add(shellArgs);
// Add log redirect params
vargs.add(&quot;1&gt;&quot; + ApplicationConstants.LOG_DIR_EXPANSION_VAR + &quot;/stdout&quot;);
vargs.add(&quot;2&gt;&quot; + ApplicationConstants.LOG_DIR_EXPANSION_VAR + &quot;/stderr&quot;);
// Get final command
StringBuilder command = new StringBuilder();
for (CharSequence str : vargs) {
command.append(str).append(&quot; &quot;);
}
List&lt;String&gt; commands = new ArrayList&lt;String&gt;();
commands.add(command.toString());
// Set up ContainerLaunchContext, setting local resource, environment,
// command and token for constructor.
// Note for tokens: Set up tokens for the container too. Today, for normal
// shell commands, the container in distribute-shell doesn't need any
// tokens. We are populating them mainly for NodeManagers to be able to
// download anyfiles in the distributed file-system. The tokens are
// otherwise also useful in cases, for e.g., when one is running a
// &quot;hadoop dfs&quot; command inside the distributed shell.
ContainerLaunchContext ctx = ContainerLaunchContext.newInstance(
localResources, shellEnv, commands, null, allTokens.duplicate(), null);
containerListener.addContainer(container.getId(), container);
nmClientAsync.startContainerAsync(container, ctx);
</pre></div></div>
<ul>
<li>
<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>
</li>
</ul>
<div class="source">
<div class="source">
<pre>try {
amRMClient.unregisterApplicationMaster(appStatus, appMessage, null);
} catch (YarnException ex) {
LOG.error(&quot;Failed to unregister application&quot;, ex);
} catch (IOException e) {
LOG.error(&quot;Failed to unregister application&quot;, e);
}
amRMClient.stop();
</pre></div></div>
</section></section><section>
<h2><a name="FAQ"></a>FAQ</h2><section>
<h3><a name="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&#x2019;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>
<div class="source">
<div class="source">
<pre>File packageFile = new File(packagePath);
URL packageUrl = ConverterUtils.getYarnUrlFromPath(
FileContext.getFileContext().makeQualified(new Path(packagePath)));
packageResource.setResource(packageUrl);
packageResource.setSize(packageFile.length());
packageResource.setTimestamp(packageFile.lastModified());
packageResource.setType(LocalResourceType.ARCHIVE);
packageResource.setVisibility(LocalResourceVisibility.APPLICATION);
resource.setMemory(memory);
containerCtx.setResource(resource);
containerCtx.setCommands(ImmutableList.of(
&quot;java -cp './package/*' some.class.to.Run &quot;
+ &quot;1&gt;&quot; + ApplicationConstants.LOG_DIR_EXPANSION_VAR + &quot;/stdout &quot;
+ &quot;2&gt;&quot; + ApplicationConstants.LOG_DIR_EXPANSION_VAR + &quot;/stderr&quot;));
containerCtx.setLocalResources(
Collections.singletonMap(&quot;package&quot;, packageResource));
appCtx.setApplicationId(appId);
appCtx.setUser(user.getShortUserName);
appCtx.setAMContainerSpec(containerCtx);
yarnClient.submitApplication(appCtx);
</pre></div></div>
<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&#x2019;s cwd, so you can just refer to the artifacts inside by using ./package/*.</p>
<p><b>Note</b>: Java&#x2019;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&#x2019;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><a name="How_do_I_get_the_ApplicationMaster.E2.80.99s_ApplicationAttemptId.3F"></a>How do I get the ApplicationMaster&#x2019;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><a name="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&#x2019;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&#x2019;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><a name="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>
<h2><a name="Useful_Links"></a>Useful Links</h2>
<ul>
<li>
<p><a href="./YARN.html">YARN Architecture</a></p>
</li>
<li>
<p><a href="./CapacityScheduler.html">YARN Capacity Scheduler</a></p>
</li>
<li>
<p><a href="./FairScheduler.html">YARN Fair Scheduler</a></p>
</li>
</ul></section><section>
<h2><a name="Sample_Code"></a>Sample Code</h2>
<p>YARN distributed shell: in <code>hadoop-yarn-applications-distributedshell</code> project after you set up your development environment.</p></section>
</div>
</div>
<div class="clear">
<hr/>
</div>
<div id="footer">
<div class="xright">
&#169; 2008-2023
Apache Software Foundation
- <a href="http://maven.apache.org/privacy-policy.html">Privacy Policy</a>.
Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven project logos are trademarks of The Apache Software Foundation.
</div>
<div class="clear">
<hr/>
</div>
</div>
</body>
</html>