Job运行分析

本文我们用来分析Job的启动过程。
下面我们按照job在server端的提交过程进行分析

JobRequestHandler

JobRequestHandler负责处理关于job的请求报文。当收到启动job的请求时,其执行startJob
函数,startJob函数的处理过程为:

  • 取出job和请求报文中的相关信息
  • 授权检查
  • 调用JobManager的start方法
private JsonBean startJob(RequestContext ctx) {
    Repository repository = RepositoryManager.getInstance().getRepository();
    String[] elements = ctx.getUrlElements();
    String jobIdentifier = elements[elements.length - 2];
    long jobId = HandlerUtils.getJobIdFromIdentifier(jobIdentifier, repository);

    // Authorization check
    AuthorizationEngine.startJob(String.valueOf(jobId));

    AuditLoggerManager.getInstance().logAuditEvent(ctx.getUserName(),
        ctx.getRequest().getRemoteAddr(), "submit", "job", String.valueOf(jobId));
    // TODO(SQOOP-1638): This should be outsourced somewhere more suitable than
    // here
    if (JobManager.getInstance().getNotificationBaseUrl() == null) {
      String url = ctx.getRequest().getRequestURL().toString();
      JobManager.getInstance().setNotificationBaseUrl(
          url.split("v1")[0] + "/v1/job/status/notification/");
    }

    MSubmission submission = JobManager.getInstance()
        .start(jobId, prepareRequestEventContext(ctx));
    return new SubmissionBean(submission);
  }

JobManager

JobManager的start方法的主要功能在于将设置JobRequest(抽象类),一个子类为MRJobRequest。MRJobRequest类包含了执行map,reduce任务的各种配置的参数。
start方法的执行过程如下:

  • 创建Submission代表执行状态
  • 创建JobRequest用于代表Job的配置信息
  • executionEngine.prepareJob设置map,reduce任务的一些参数。包括mapper.class,等
  • 判断Job是否已经执行
  • submissionEngine调用submit方法,提交任务
  • 将任务的执行状态Submission即持久化保存在Repositor中。
 public MSubmission start(long jobId, HttpEventContext ctx) {

    MSubmission mSubmission = createJobSubmission(ctx, jobId);
    JobRequest jobRequest = createJobRequest(jobId, mSubmission);
    // Bootstrap job to execute in the configured execution engine
    prepareJob(jobRequest);
    // Make sure that this job id is not currently running and submit the job
    // only if it's not.
    synchronized (getClass()) {
      MSubmission lastSubmission = RepositoryManager.getInstance().getRepository()
          .findLastSubmissionForJob(jobId);
      if (lastSubmission != null && lastSubmission.getStatus().isRunning()) {
        throw new SqoopException(DriverError.DRIVER_0002, "Job with id " + jobId);
      }
      // NOTE: the following is a blocking call
      boolean success = submissionEngine.submit(jobRequest);
      if (!success) {
        invokeDestroyerOnJobFailure(jobRequest);
        mSubmission.setStatus(SubmissionStatus.FAILURE_ON_SUBMIT);
      }
      // persist submission record to repository.
      // on failure we persist the FAILURE status, on success it is the SUCCESS
      // status ( which is the default one)
      RepositoryManager.getInstance().getRepository().createSubmission(mSubmission);
    }
    return mSubmission;
  }

submissionEngine

MapreduceSubmissionEngine的submit方法利用MRJobRequest中的信息,配置mapreduce 任务job. 设置完成之后,向hadoop集群提交任务
源代码如下:

  public boolean submit(JobRequest mrJobRequest) {
    // We're supporting only map reduce jobs
    MRJobRequest request = (MRJobRequest) mrJobRequest;

    // Clone global configuration
    Configuration configuration = new Configuration(globalConfiguration);

    // Serialize driver context into job configuration
    for(Map.Entry<String, String> entry: request.getDriverContext()) {
      if (entry.getValue() == null) {
        LOG.warn("Ignoring null driver context value for key " + entry.getKey());
        continue;
      }
      configuration.set(entry.getKey(), entry.getValue());
    }

    // Serialize connector context as a sub namespace
    for(Map.Entry<String, String> entry : request.getConnectorContext(Direction.FROM)) {
      if (entry.getValue() == null) {
        LOG.warn("Ignoring null connector context value for key " + entry.getKey());
        continue;
      }
      configuration.set(
        MRJobConstants.PREFIX_CONNECTOR_FROM_CONTEXT + entry.getKey(),
        entry.getValue());
    }

    for(Map.Entry<String, String> entry : request.getConnectorContext(Direction.TO)) {
      if (entry.getValue() == null) {
        LOG.warn("Ignoring null connector context value for key " + entry.getKey());
        continue;
      }
      configuration.set(
          MRJobConstants.PREFIX_CONNECTOR_TO_CONTEXT + entry.getKey(),
          entry.getValue());
    }

    // Set up notification URL if it's available
    if(request.getNotificationUrl() != null) {
      configuration.set("job.end.notification.url", request.getNotificationUrl());
    }

    // Turn off speculative execution
    configuration.setBoolean("mapred.map.tasks.speculative.execution", false);
    configuration.setBoolean("mapred.reduce.tasks.speculative.execution", false);

    // Promote all required jars to the job
    configuration.set("tmpjars", StringUtils.join(request.getJars(), ","));

    try {
      Job job = new Job(configuration);

      // link configs
      MRConfigurationUtils.setConnectorLinkConfig(Direction.FROM, job, request.getConnectorLinkConfig(Direction.FROM));
      MRConfigurationUtils.setConnectorLinkConfig(Direction.TO, job, request.getConnectorLinkConfig(Direction.TO));

      // from and to configs
      MRConfigurationUtils.setConnectorJobConfig(Direction.FROM, job, request.getJobConfig(Direction.FROM));
      MRConfigurationUtils.setConnectorJobConfig(Direction.TO, job, request.getJobConfig(Direction.TO));

      MRConfigurationUtils.setDriverConfig(job, request.getDriverConfig());
      MRConfigurationUtils.setConnectorSchema(Direction.FROM, job, request.getJobSubmission().getFromSchema());
      MRConfigurationUtils.setConnectorSchema(Direction.TO, job, request.getJobSubmission().getToSchema());

      if(request.getJobName() != null) {
        job.setJobName("Sqoop: " + request.getJobName());
      } else {
        job.setJobName("Sqoop job with id: " + request.getJobId());
      }

      job.setInputFormatClass(request.getInputFormatClass());

      job.setMapperClass(request.getMapperClass());
      job.setMapOutputKeyClass(request.getMapOutputKeyClass());
      job.setMapOutputValueClass(request.getMapOutputValueClass());

      // Set number of reducers as number of configured loaders  or suppress
      // reduce phase entirely if loaders are not set at all.
      if(request.getLoaders() != null) {
        job.setNumReduceTasks(request.getLoaders());
      } else {
        job.setNumReduceTasks(0);
      }

      job.setOutputFormatClass(request.getOutputFormatClass());
      job.setOutputKeyClass(request.getOutputKeyClass());
      job.setOutputValueClass(request.getOutputValueClass());

      // If we're in local mode than wait on completion. Local job runner do not
      // seems to be exposing API to get previously submitted job which makes
      // other methods of the submission engine quite useless.
      // NOTE: The minicluster mode is not local. It runs similar to a real MR cluster but
      // only that it is in the same JVM
      if (isLocal()) {
        submitToLocalRunner(request, job);
      } else {
        submitToCluster(request, job);
      }
      LOG.debug("Executed new map-reduce job with id " + job.getJobID().toString());
    } catch (Exception e) {
      SubmissionError error = new SubmissionError();
      error.setErrorSummary(e.toString());
      StringWriter writer = new StringWriter();
      e.printStackTrace(new PrintWriter(writer));
      writer.flush();
      error.setErrorDetails(writer.toString());

      request.getJobSubmission().setError(error);
      LOG.error("Error in submitting job", e);
      return false;
    }
    return true;
  }

SqoopMapper

SqoopMapper类是完成map,reduce任务的Mapper类。其主要是利用Extractor从数据源(目的地)抽取(写入数据)

Extractor

源代码中对于Extractor的描述如下:


/**
 * This allows connector to extract data from a source system
 * based on each partition.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public abstract class Extractor<LinkConfiguration, FromJobConfiguration, SqoopPartition> {

  /**
   * Extract data from source and pass them into the Sqoop.
   *
   * @param context Extractor context object
   * @param linkConfiguration link configuration object
   * @param jobConfiguration FROM job configuration object
   * @param partition Partition that this extracter should work on
   */
  public abstract void extract(ExtractorContext context,
                               LinkConfiguration linkConfiguration,
                               FromJobConfiguration jobConfiguration,
                               SqoopPartition partition);

  /**
   * Return the number of rows read by the last call to
   * {@linkplain Extractor#extract(org.apache.sqoop.job.etl.ExtractorContext, java.lang.Object, java.lang.Object, Partition) }
   * method. This method returns only the number of rows read in the last call,
   * and not a cumulative total of the number of rows read by this Extractor
   * since its creation. If no calls were made to the run method, this method's
   * behavior is undefined.
   *
   * @return the number of rows read by the last call to
   * {@linkplain Extractor#extract(org.apache.sqoop.job.etl.ExtractorContext, java.lang.Object, java.lang.Object, Partition) }
   */
  public abstract long getRowsRead();

}

GenericJdbcExtractor

GenericJdbcExtractor 继承Extractor。其是从jdbc类的数据源中读取数据.
其源代码如下:

 @Override
  public void extract(ExtractorContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig, GenericJdbcPartition partition) {
    GenericJdbcExecutor executor = new GenericJdbcExecutor(linkConfig.linkConfig);

    String query = context.getString(GenericJdbcConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL);
    String conditions = partition.getConditions();
    query = query.replace(GenericJdbcConnectorConstants.SQL_CONDITIONS_TOKEN, conditions);
    LOG.info("Using query: " + query);

    rowsRead = 0;
    ResultSet resultSet = executor.executeQuery(query);

    Schema schema = context.getSchema();
    Column[] schemaColumns = schema.getColumnsArray();
    try {
      ResultSetMetaData metaData = resultSet.getMetaData();
      int columnCount = metaData.getColumnCount();
      if (schemaColumns.length != columnCount) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0021, schemaColumns.length + ":" + columnCount);
      }
      while (resultSet.next()) {
        Object[] array = new Object[columnCount];
        for (int i = 0; i < columnCount; i++) {
          if(resultSet.getObject(i + 1) == null) {
            array[i] = null ;
            continue;
          }
          // check type of the column
          Column schemaColumn = schemaColumns[i];
          switch (schemaColumn.getType()) {
          case DATE:
            // convert the sql date to JODA time as prescribed the Sqoop IDF spec
            array[i] = LocalDate.fromDateFields((java.sql.Date)resultSet.getObject(i + 1));
            break;
          case DATE_TIME:
            // convert the sql date time to JODA time as prescribed the Sqoop IDF spec
            array[i] = LocalDateTime.fromDateFields((java.sql.Timestamp)resultSet.getObject(i + 1));
            break;
          case TIME:
            // convert the sql time to JODA time as prescribed the Sqoop IDF spec
            array[i] = LocalTime.fromDateFields((java.sql.Time)resultSet.getObject(i + 1));
            break;
          default:
            //for anything else
            array[i] = resultSet.getObject(i + 1);

          }
        }
        context.getDataWriter().writeArrayRecord(array);
        rowsRead++;
      }
    } catch (SQLException e) {
      throw new SqoopException(
          GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0004, e);

    } finally {
      executor.close();
    }
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280

推荐阅读更多精彩内容