转自:http://blog.csdn.net/lihm0_1/article/details/22186833

YARN作业提交的客户端仍然使用RunJar类,和MR1一样,可参考 
http://blog.csdn.net/lihm0_1/article/details/13629375
在1.x中是向JobTracker提交,而在2.x中换成了ResourceManager,客户端的代理对象也有所变动,换成了YarnRunner,但大致流程和1类似,主要的流程集中在JobSubmitter.submitJobInternal中,包括检测输出目录合法性,设置作业提交信息(主机和用户),获得JobID,向HDFS中拷贝作业所需文件(Job.jar Job.xml split文件等)最有执行作业提交。这里仍然以WordCount为例介绍提交流程.

  1. public static void main(String[] args) throws Exception {
  2. // 创建一个job
  3. Configuration conf = new Configuration();
  4. conf.set("mapreduce.job.queuename", "p1");
  5. @SuppressWarnings("deprecation")
  6. Job job = new Job(conf, "WordCount");
  7. job.setJarByClass(WordCount.class);
  8. job.setJar("/root/wordcount-2.3.0.jar");
  9. // 设置输入输出类型
  10. job.setOutputKeyClass(Text.class);
  11. job.setOutputValueClass(IntWritable.class);
  12. // 设置map和reduce类
  13. job.setMapperClass(WordCountMapper.class);
  14. job.setReducerClass(WordCountReduce.class);
  15. // 设置输入输出流
  16. FileInputFormat.addInputPath(job, new Path("/tmp/a.txt"));
  17. FileOutputFormat.setOutputPath(job, new Path("/tmp/output"));
  18. job.waitForCompletion(true);//此处进入作业提交流程,然后循环监控作业状态
  19. }

此处和1.x相同,提交作业,循环监控作业状态

  1. public boolean waitForCompletion(boolean verbose
  2. ) throws IOException, InterruptedException,
  3. ClassNotFoundException {
  4. if (state == JobState.DEFINE) {
  5. submit();//提交
  6. }
  7. if (verbose) {
  8. monitorAndPrintJob();
  9. } else {
  10. // get the completion poll interval from the client.
  11. int completionPollIntervalMillis =
  12. Job.getCompletionPollInterval(cluster.getConf());
  13. while (!isComplete()) {
  14. try {
  15. Thread.sleep(completionPollIntervalMillis);
  16. } catch (InterruptedException ie) {
  17. }
  18. }
  19. }
  20. return isSuccessful();
  21. }

主要分析submit函数,来看作业是如何提交的,此处已经和1.x不同。但仍分为两个阶段1、连接master 2、作业提交

  1. public void submit()
  2. throws IOException, InterruptedException, ClassNotFoundException {
  3. ensureState(JobState.DEFINE);
  4. setUseNewAPI();
  5. //连接RM
  6. connect();
  7. final JobSubmitter submitter =
  8. getJobSubmitter(cluster.getFileSystem(), cluster.getClient());
  9. status = ugi.doAs(new PrivilegedExceptionAction<JobStatus>() {
  10. public JobStatus run() throws IOException, InterruptedException,
  11. ClassNotFoundException {
  12. //提交作业
  13. return submitter.submitJobInternal(Job.this, cluster);
  14. }
  15. });
  16. state = JobState.RUNNING;
  17. LOG.info("The url to track the job: " + getTrackingURL());
  18. }

连接master时会建立Cluster实例,下面是Cluster构造函数,其中重点初始化部分

  1. public Cluster(InetSocketAddress jobTrackAddr, Configuration conf)
  2. throws IOException {
  3. this.conf = conf;
  4. this.ugi = UserGroupInformation.getCurrentUser();
  5. initialize(jobTrackAddr, conf);
  6. }

创建客户端代理阶段用到了java.util.ServiceLoader,目前2.3.0版本包含两个LocalClientProtocolProvider(本地作业) YarnClientProtocolProvider(Yarn作业),此处会根据mapreduce.framework.name的配置创建相应的客户端

  1. private void initialize(InetSocketAddress jobTrackAddr, Configuration conf)
  2. throws IOException {
  3. synchronized (frameworkLoader) {
  4. for (ClientProtocolProvider provider : frameworkLoader) {
  5. LOG.debug("Trying ClientProtocolProvider : "
  6. + provider.getClass().getName());
  7. ClientProtocol clientProtocol = null;
  8. try {
  9. if (jobTrackAddr == null) {
  10. //创建YARNRunner对象
  11. clientProtocol = provider.create(conf);
  12. } else {
  13. clientProtocol = provider.create(jobTrackAddr, conf);
  14. }
  15. //初始化Cluster内部成员变量
  16. if (clientProtocol != null) {
  17. clientProtocolProvider = provider;
  18. client = clientProtocol;
  19. LOG.debug("Picked " + provider.getClass().getName()
  20. + " as the ClientProtocolProvider");
  21. break;
  22. }
  23. else {
  24. LOG.debug("Cannot pick " + provider.getClass().getName()
  25. + " as the ClientProtocolProvider - returned null protocol");
  26. }
  27. }
  28. catch (Exception e) {
  29. LOG.info("Failed to use " + provider.getClass().getName()
  30. + " due to error: " + e.getMessage());
  31. }
  32. }
  33. }
  34. //异常处理,如果此处出现异常,则证明加载的jar包有问题,YarnRunner所处的jar不存在?
  35. if (null == clientProtocolProvider || null == client) {
  36. throw new IOException(
  37. "Cannot initialize Cluster. Please check your configuration for "
  38. + MRConfig.FRAMEWORK_NAME
  39. + " and the correspond server addresses.");
  40. }
  41. }

provider创建代理实际是创建了一个YranRunner对象,因为我们这里提交的不是Local的,而是Yarn作业

  1. @Override
  2. public ClientProtocol create(Configuration conf) throws IOException {
  3. if (MRConfig.YARN_FRAMEWORK_NAME.equals(conf.get(MRConfig.FRAMEWORK_NAME))) {
  4. return new YARNRunner(conf);
  5. }
  6. return null;
  7. }

创建客户端代理的流程如下:
Cluster->ClientProtocol(YarnRunner)->ResourceMgrDelegate->client(YarnClientImpl)->rmClient(ApplicationClientProtocol)
在YarnClientImpl的serviceStart阶段会创建RPC代理,注意其中的协议。

  1. protected void serviceStart() throws Exception {
  2. try {
  3. rmClient = ClientRMProxy.createRMProxy(getConfig(),
  4. ApplicationClientProtocol.class);
  5. } catch (IOException e) {
  6. throw new YarnRuntimeException(e);
  7. }
  8. super.serviceStart();
  9. }

YarnRunner的构造函数如下:

  1. public YARNRunner(Configuration conf, ResourceMgrDelegate resMgrDelegate,
  2. ClientCache clientCache) {
  3. this.conf = conf;
  4. try {
  5. this.resMgrDelegate = resMgrDelegate;
  6. this.clientCache = clientCache;
  7. this.defaultFileContext = FileContext.getFileContext(this.conf);
  8. } catch (UnsupportedFileSystemException ufe) {
  9. throw new RuntimeException("Error in instantiating YarnClient", ufe);
  10. }
  11. }

下面看最核心的提交部分JobSubmitter.submitJobInternal

  1. JobStatus submitJobInternal(Job job, Cluster cluster)
  2. throws ClassNotFoundException, InterruptedException, IOException {
  3. //检测输出目录合法性,是否已存在,或未设置
  4. checkSpecs(job);
  5. Configuration conf = job.getConfiguration();
  6. addMRFrameworkToDistributedCache(conf);
  7. //获得登录区,用以存放作业执行过程中用到的文件,默认位置/tmp/hadoop-yarn/staging/root/.staging ,可通过yarn.app.mapreduce.am.staging-dir修改
  8. Path jobStagingArea = JobSubmissionFiles.getStagingDir(cluster, conf);
  9. //主机名和地址设置
  10. InetAddress ip = InetAddress.getLocalHost();
  11. if (ip != null) {
  12. submitHostAddress = ip.getHostAddress();
  13. submitHostName = ip.getHostName();
  14. conf.set(MRJobConfig.JOB_SUBMITHOST,submitHostName);
  15. conf.set(MRJobConfig.JOB_SUBMITHOSTADDR,submitHostAddress);
  16. }
  17. //获取新的JobID,此处需要RPC调用
  18. JobID jobId = submitClient.getNewJobID();
  19. job.setJobID(jobId);
  20. //获取提交目录:/tmp/hadoop-yarn/staging/root/.staging/job_1395778831382_0002
  21. Path submitJobDir = new Path(jobStagingArea, jobId.toString());
  22. JobStatus status = null;
  23. try {
  24. conf.set(MRJobConfig.USER_NAME,
  25. UserGroupInformation.getCurrentUser().getShortUserName());
  26. conf.set("hadoop.http.filter.initializers",
  27. "org.apache.hadoop.yarn.server.webproxy.amfilter.AmFilterInitializer");
  28. conf.set(MRJobConfig.MAPREDUCE_JOB_DIR, submitJobDir.toString());
  29. LOG.debug("Configuring job " + jobId + " with " + submitJobDir
  30. + " as the submit dir");
  31. // get delegation token for the dir
  32. TokenCache.obtainTokensForNamenodes(job.getCredentials(),
  33. new Path[] { submitJobDir }, conf);
  34. populateTokenCache(conf, job.getCredentials());
  35. // generate a secret to authenticate shuffle transfers
  36. if (TokenCache.getShuffleSecretKey(job.getCredentials()) == null) {
  37. KeyGenerator keyGen;
  38. try {
  39. keyGen = KeyGenerator.getInstance(SHUFFLE_KEYGEN_ALGORITHM);
  40. keyGen.init(SHUFFLE_KEY_LENGTH);
  41. } catch (NoSuchAlgorithmException e) {
  42. throw new IOException("Error generating shuffle secret key", e);
  43. }
  44. SecretKey shuffleKey = keyGen.generateKey();
  45. TokenCache.setShuffleSecretKey(shuffleKey.getEncoded(),
  46. job.getCredentials());
  47. }
  48. //向集群中拷贝所需文件,下面会单独分析(1)
  49. copyAndConfigureFiles(job, submitJobDir);
  50. Path submitJobFile = JobSubmissionFiles.getJobConfPath(submitJobDir);
  51. // 写分片文件job.split job.splitmetainfo,具体写入过程与MR1相同,可参考以前文章
  52. LOG.debug("Creating splits at " + jtFs.makeQualified(submitJobDir));
  53. int maps = writeSplits(job, submitJobDir);
  54. conf.setInt(MRJobConfig.NUM_MAPS, maps);
  55. LOG.info("number of splits:" + maps);
  56. // write "queue admins of the queue to which job is being submitted"
  57. // to job file.
  58. //设置队列名
  59. String queue = conf.get(MRJobConfig.QUEUE_NAME,
  60. JobConf.DEFAULT_QUEUE_NAME);
  61. AccessControlList acl = submitClient.getQueueAdmins(queue);
  62. conf.set(toFullPropertyName(queue,
  63. QueueACL.ADMINISTER_JOBS.getAclName()), acl.getAclString());
  64. // removing jobtoken referrals before copying the jobconf to HDFS
  65. // as the tasks don't need this setting, actually they may break
  66. // because of it if present as the referral will point to a
  67. // different job.
  68. TokenCache.cleanUpTokenReferral(conf);
  69. if (conf.getBoolean(
  70. MRJobConfig.JOB_TOKEN_TRACKING_IDS_ENABLED,
  71. MRJobConfig.DEFAULT_JOB_TOKEN_TRACKING_IDS_ENABLED)) {
  72. // Add HDFS tracking ids
  73. ArrayList<String> trackingIds = new ArrayList<String>();
  74. for (Token<? extends TokenIdentifier> t :
  75. job.getCredentials().getAllTokens()) {
  76. trackingIds.add(t.decodeIdentifier().getTrackingId());
  77. }
  78. conf.setStrings(MRJobConfig.JOB_TOKEN_TRACKING_IDS,
  79. trackingIds.toArray(new String[trackingIds.size()]));
  80. }
  81. // Write job file to submit dir
  82. //写入job.xml
  83. writeConf(conf, submitJobFile);
  84. //
  85. // Now, actually submit the job (using the submit name)
  86. //这里才开始真正提交,见下面分析(2)
  87. printTokens(jobId, job.getCredentials());
  88. status = submitClient.submitJob(
  89. jobId, submitJobDir.toString(), job.getCredentials());
  90. if (status != null) {
  91. return status;
  92. } else {
  93. throw new IOException("Could not launch job");
  94. }
  95. } finally {
  96. if (status == null) {
  97. LOG.info("Cleaning up the staging area " + submitJobDir);
  98. if (jtFs != null && submitJobDir != null)
  99. jtFs.delete(submitJobDir, true);
  100. }
  101. }
  102. }

(1)文件拷贝过程如下,默认副本数为10

  1. private void copyAndConfigureFiles(Job job, Path jobSubmitDir)
  2. throws IOException {
  3. Configuration conf = job.getConfiguration();
  4. short replication = (short)conf.getInt(Job.SUBMIT_REPLICATION, 10);
  5. //开始拷贝
  6. copyAndConfigureFiles(job, jobSubmitDir, replication);
  7. // Set the working directory
  8. if (job.getWorkingDirectory() == null) {
  9. job.setWorkingDirectory(jtFs.getWorkingDirectory());
  10. }
  11. }

下面是具体文件拷贝过程,注释里写的也比较清楚了

  1. // configures -files, -libjars and -archives.
  2. private void copyAndConfigureFiles(Job job, Path submitJobDir,
  3. short replication) throws IOException {
  4. Configuration conf = job.getConfiguration();
  5. if (!(conf.getBoolean(Job.USED_GENERIC_PARSER, false))) {
  6. LOG.warn("Hadoop command-line option parsing not performed. " +
  7. "Implement the Tool interface and execute your application " +
  8. "with ToolRunner to remedy this.");
  9. }
  10. // get all the command line arguments passed in by the user conf
  11. String files = conf.get("tmpfiles");
  12. String libjars = conf.get("tmpjars");
  13. String archives = conf.get("tmparchives");
  14. String jobJar = job.getJar();
  15. //
  16. // Figure out what fs the JobTracker is using.  Copy the
  17. // job to it, under a temporary name.  This allows DFS to work,
  18. // and under the local fs also provides UNIX-like object loading
  19. // semantics.  (that is, if the job file is deleted right after
  20. // submission, we can still run the submission to completion)
  21. //
  22. // Create a number of filenames in the JobTracker's fs namespace
  23. LOG.debug("default FileSystem: " + jtFs.getUri());
  24. if (jtFs.exists(submitJobDir)) {
  25. throw new IOException("Not submitting job. Job directory " + submitJobDir
  26. +" already exists!! This is unexpected.Please check what's there in" +
  27. " that directory");
  28. }
  29. submitJobDir = jtFs.makeQualified(submitJobDir);
  30. submitJobDir = new Path(submitJobDir.toUri().getPath());
  31. FsPermission mapredSysPerms = new FsPermission(JobSubmissionFiles.JOB_DIR_PERMISSION);
  32. //创建工作目录
  33. FileSystem.mkdirs(jtFs, submitJobDir, mapredSysPerms);
  34. Path filesDir = JobSubmissionFiles.getJobDistCacheFiles(submitJobDir);
  35. Path archivesDir = JobSubmissionFiles.getJobDistCacheArchives(submitJobDir);
  36. Path libjarsDir = JobSubmissionFiles.getJobDistCacheLibjars(submitJobDir);
  37. // add all the command line files/ jars and archive
  38. // first copy them to jobtrackers filesystem
  39. //建立上述所需目录
  40. if (files != null) {
  41. FileSystem.mkdirs(jtFs, filesDir, mapredSysPerms);
  42. String[] fileArr = files.split(",");
  43. for (String tmpFile: fileArr) {
  44. URI tmpURI = null;
  45. try {
  46. tmpURI = new URI(tmpFile);
  47. } catch (URISyntaxException e) {
  48. throw new IllegalArgumentException(e);
  49. }
  50. Path tmp = new Path(tmpURI);
  51. Path newPath = copyRemoteFiles(filesDir, tmp, conf, replication);
  52. try {
  53. URI pathURI = getPathURI(newPath, tmpURI.getFragment());
  54. DistributedCache.addCacheFile(pathURI, conf);
  55. } catch(URISyntaxException ue) {
  56. //should not throw a uri exception
  57. throw new IOException("Failed to create uri for " + tmpFile, ue);
  58. }
  59. }
  60. }
  61. if (libjars != null) {
  62. FileSystem.mkdirs(jtFs, libjarsDir, mapredSysPerms);
  63. String[] libjarsArr = libjars.split(",");
  64. for (String tmpjars: libjarsArr) {
  65. Path tmp = new Path(tmpjars);
  66. Path newPath = copyRemoteFiles(libjarsDir, tmp, conf, replication);
  67. DistributedCache.addFileToClassPath(
  68. new Path(newPath.toUri().getPath()), conf);
  69. }
  70. }
  71. if (archives != null) {
  72. FileSystem.mkdirs(jtFs, archivesDir, mapredSysPerms);
  73. String[] archivesArr = archives.split(",");
  74. for (String tmpArchives: archivesArr) {
  75. URI tmpURI;
  76. try {
  77. tmpURI = new URI(tmpArchives);
  78. } catch (URISyntaxException e) {
  79. throw new IllegalArgumentException(e);
  80. }
  81. Path tmp = new Path(tmpURI);
  82. Path newPath = copyRemoteFiles(archivesDir, tmp, conf,
  83. replication);
  84. try {
  85. URI pathURI = getPathURI(newPath, tmpURI.getFragment());
  86. DistributedCache.addCacheArchive(pathURI, conf);
  87. } catch(URISyntaxException ue) {
  88. //should not throw an uri excpetion
  89. throw new IOException("Failed to create uri for " + tmpArchives, ue);
  90. }
  91. }
  92. }
  93. if (jobJar != null) {   // copy jar to JobTracker's fs
  94. // use jar name if job is not named.
  95. if ("".equals(job.getJobName())){
  96. job.setJobName(new Path(jobJar).getName());
  97. }
  98. Path jobJarPath = new Path(jobJar);
  99. URI jobJarURI = jobJarPath.toUri();
  100. // If the job jar is already in fs, we don't need to copy it from local fs
  101. if (jobJarURI.getScheme() == null || jobJarURI.getAuthority() == null
  102. || !(jobJarURI.getScheme().equals(jtFs.getUri().getScheme())
  103. && jobJarURI.getAuthority().equals(
  104. jtFs.getUri().getAuthority()))) {
  105. //拷贝wordcount.jar,注意拷贝过去后会重命名为job.jar,副本数为10
  106. copyJar(jobJarPath, JobSubmissionFiles.getJobJar(submitJobDir),
  107. replication);
  108. job.setJar(JobSubmissionFiles.getJobJar(submitJobDir).toString());
  109. }
  110. } else {
  111. LOG.warn("No job jar file set.  User classes may not be found. "+
  112. "See Job or Job#setJar(String).");
  113. }
  114. //  set the timestamps of the archives and files
  115. //  set the public/private visibility of the archives and files
  116. ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf);
  117. // get DelegationToken for each cached file
  118. ClientDistributedCacheManager.getDelegationTokens(conf, job
  119. .getCredentials());
  120. }

(2)真正的作业提交部分

    1. @Override
    2. public JobStatus submitJob(JobID jobId, String jobSubmitDir, Credentials ts)
    3. throws IOException, InterruptedException {
    4. addHistoryToken(ts);
    5. // Construct necessary information to start the MR AM
    6. ApplicationSubmissionContext appContext =
    7. createApplicationSubmissionContext(conf, jobSubmitDir, ts);
    8. // Submit to ResourceManager
    9. try {
    10. ApplicationId applicationId =
    11. resMgrDelegate.submitApplication(appContext);
    12. ApplicationReport appMaster = resMgrDelegate
    13. .getApplicationReport(applicationId);
    14. String diagnostics =
    15. (appMaster == null ?
    16. "application report is null" : appMaster.getDiagnostics());
    17. if (appMaster == null
    18. || appMaster.getYarnApplicationState() == YarnApplicationState.FAILED
    19. || appMaster.getYarnApplicationState() == YarnApplicationState.KILLED) {
    20. throw new IOException("Failed to run job : " +
    21. diagnostics);
    22. }
    23. return clientCache.getClient(jobId).getJobStatus(jobId);
    24. } catch (YarnException e) {
    25. throw new IOException(e);
    26. }
    27. }
 

Hadoop2.x Yarn作业提交(客户端)的更多相关文章

  1. hadoop2.7之作业提交详解(下)

    接着作业提交详解(上)继续写:在上一篇(hadoop2.7之作业提交详解(上))中已经讲到了YARNRunner.submitJob() [WordCount.main() -> Job.wai ...

  2. hadoop2.7之作业提交详解(上)

    根据wordcount进行分析: import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; impo ...

  3. YARN作业提交流程剖析

    YARN(MapReduce2) Yet Another Resource Negotiator / YARN Application Resource Negotiator对于节点数超出4000的大 ...

  4. yarn作业提交过程源码

    记录源码细节,内部有中文注释 Client 端: //最终通过ApplicationClientProtocol协议提交到RM端的ClientRMService内 package org.apache ...

  5. hadoop2.7作业提交详解之文件分片

    在前面一篇文章中(hadoop2.7之作业提交详解(上))中涉及到文件的分片. JobSubmitter.submitJobInternal方法中调用了int maps = writeSplits(j ...

  6. hadoop2 作业执行过程之作业提交

    hadoop2.2.0.centos6.5 hadoop任务的提交常用的两种,一种是测试常用的IDE远程提交,另一种就是生产上用的客户端命令行提交 通用的任务程序提交步骤为: 1.将程序打成jar包: ...

  7. Spark作业提交至Yarn上执行的 一个异常

    (1)控制台Yarn(Cluster模式)打印的异常日志: client token: N/A         diagnostics: Application application_1584359 ...

  8. 【Hadoop代码笔记】Hadoop作业提交之客户端作业提交

    1.      概要描述仅仅描述向Hadoop提交作业的第一步,即调用Jobclient的submitJob方法,向Hadoop提交作业. 2.      详细描述Jobclient使用内置的JobS ...

  9. MapReduce源码分析之新API作业提交(二):连接集群

    MapReduce作业提交时连接集群是通过Job的connect()方法实现的,它实际上是构造集群Cluster实例cluster,代码如下: private synchronized void co ...

随机推荐

  1. T-SQL 之 运算符

    1.算术运算符 [1] +:加 [2] -:减 [3] *:乘 [4] /:除 [5] %:模除取余 2.位运算符 [1] &(与,and): 按位逻辑与运算 [2] |(或,or): 按位逻 ...

  2. AsyncTask doinbackground onProgressUpdate onCancelled onPostExecute的基本使用

    对于异步操作的原理我就不讲了.在这我着重讲怎么使用异步操作的doinbackground onProgressUpdate onCancelled onPostExecute这四个方法 doinbac ...

  3. android KK版本号收到短信后,点亮屏的操作

    alps/packages/apps/mms/src/comandroid\mms\transation\MessagingNotification.java private static void ...

  4. git:could not open a connection to your authentication agent

    git:could not open a connection to your authentication agent   错误: vagrant@homestead:~/Code/sample$ ...

  5. 搭建Android开发环境之旅

    1.首先要下载相关的软件 1). JDK 6 以上 2). eclipse( Version 3.6.2  or higher ) 点击下载 3). SDK(android-sdk_r18-windo ...

  6. android源码相关网站

    https://android.googlesource.com/ google的android源码网站 http://source.android.com/ android网站 git://code ...

  7. 在eclipse中将android工程打包生成apk文件

    1.)生成keystore 按照下面的命令行 在C:\Program Files\Java\jdk1.6.0_10\bin>目录下,输入keytool -genkey -alias androi ...

  8. IO多路复用之epoll

    1.基本知识 epoll是在2.6内核中提出的,是之前的select和poll的增强版本.相对于select和poll来说,epoll更加灵活,没有描述符限制.epoll使用一个文件描述符管理多个描述 ...

  9. UML建模学习3:UML基本构造块之关系

    今天我们来看UML基本构造块的还有一个要素--关系. UML中有表示基本图示符号之间的关系,它们是:依赖(dependency).泛化(generalization,也有的称继承).实 现(reali ...

  10. unity5, 在mac下多开

    mac上app的多开与app本身无关,而是系统本身的功能,使用命令 open -n 就可以实现打开某应用程序的一个新实例(自行输入man open查看含义). 参考:http://mac-how-to ...