flink - accumulator

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
简介:

读accumlator

JobManager

在job finish的时候会汇总accumulator的值,

复制代码
newJobStatus match {
  case JobStatus.FINISHED =>
  try {
    val accumulatorResults = executionGraph.getAccumulatorsSerialized()
    val result = new SerializedJobExecutionResult(
      jobID,
      jobInfo.duration,
      accumulatorResults)

    jobInfo.client ! decorateMessage(JobResultSuccess(result))
  }
复制代码

 

在client请求accumulation时,

复制代码
public Map<String, Object> getAccumulators(JobID jobID, ClassLoader loader) throws Exception {
    ActorGateway jobManagerGateway = getJobManagerGateway();
    
    Future<Object> response;
    try {
        response = jobManagerGateway.ask(new RequestAccumulatorResults(jobID), timeout);
    } catch (Exception e) {
        throw new Exception("Failed to query the job manager gateway for accumulators.", e);
    }
复制代码

 

消息传到job manager

case message: AccumulatorMessage => handleAccumulatorMessage(message)
复制代码
private def handleAccumulatorMessage(message: AccumulatorMessage): Unit = {
message match {
  case RequestAccumulatorResults(jobID) =>
    try {
      currentJobs.get(jobID) match {
        case Some((graph, jobInfo)) =>
          val accumulatorValues = graph.getAccumulatorsSerialized()
          sender() ! decorateMessage(AccumulatorResultsFound(jobID, accumulatorValues))
        case None =>
          archive.forward(message)
      }
    }
复制代码

 

ExecuteGraph

获取accumulator的值

复制代码
/**
 * Gets a serialized accumulator map.
 * @return The accumulator map with serialized accumulator values.
 * @throws IOException
 */
public Map<String, SerializedValue<Object>> getAccumulatorsSerialized() throws IOException {

    Map<String, Accumulator<?, ?>> accumulatorMap = aggregateUserAccumulators();

    Map<String, SerializedValue<Object>> result = new HashMap<String, SerializedValue<Object>>();
    for (Map.Entry<String, Accumulator<?, ?>> entry : accumulatorMap.entrySet()) {
        result.put(entry.getKey(), new SerializedValue<Object>(entry.getValue().getLocalValue()));
    }

    return result;
}
复制代码

 

execution的accumulator聚合,

复制代码
/**
 * Merges all accumulator results from the tasks previously executed in the Executions.
 * @return The accumulator map
 */
public Map<String, Accumulator<?,?>> aggregateUserAccumulators() {

    Map<String, Accumulator<?, ?>> userAccumulators = new HashMap<String, Accumulator<?, ?>>();

    for (ExecutionVertex vertex : getAllExecutionVertices()) {
        Map<String, Accumulator<?, ?>> next = vertex.getCurrentExecutionAttempt().getUserAccumulators();
        if (next != null) {
            AccumulatorHelper.mergeInto(userAccumulators, next);
        }
    }

    return userAccumulators;
}
复制代码

具体merge的逻辑,

复制代码
public static void mergeInto(Map<String, Accumulator<?, ?>> target, Map<String, Accumulator<?, ?>> toMerge) {
    for (Map.Entry<String, Accumulator<?, ?>> otherEntry : toMerge.entrySet()) {
        Accumulator<?, ?> ownAccumulator = target.get(otherEntry.getKey());
        if (ownAccumulator == null) {
            // Create initial counter (copy!)
            target.put(otherEntry.getKey(), otherEntry.getValue().clone());
        }
        else {
            // Both should have the same type
            AccumulatorHelper.compareAccumulatorTypes(otherEntry.getKey(),
                    ownAccumulator.getClass(), otherEntry.getValue().getClass());
            // Merge target counter with other counter
            mergeSingle(ownAccumulator, otherEntry.getValue());
        }
    }
}
复制代码

 

更新accumulator

JobManager

收到task发来的heartbeat,其中附带accumulators

case Heartbeat(instanceID, metricsReport, accumulators) =>
  updateAccumulators(accumulators)

根据jobid,更新到ExecutionGraph

复制代码
private def updateAccumulators(accumulators : Seq[AccumulatorSnapshot]) = {
    accumulators foreach {
      case accumulatorEvent =>
        currentJobs.get(accumulatorEvent.getJobID) match {
          case Some((jobGraph, jobInfo)) =>
            future {
              jobGraph.updateAccumulators(accumulatorEvent)
            }(context.dispatcher)
          case None =>
          // ignore accumulator values for old job
        }
    }
}
复制代码

根据ExecutionAttemptID, 更新Execution中

复制代码
/**
 * Updates the accumulators during the runtime of a job. Final accumulator results are transferred
 * through the UpdateTaskExecutionState message.
 * @param accumulatorSnapshot The serialized flink and user-defined accumulators
 */
public void updateAccumulators(AccumulatorSnapshot accumulatorSnapshot) {
    Map<AccumulatorRegistry.Metric, Accumulator<?, ?>> flinkAccumulators;
    Map<String, Accumulator<?, ?>> userAccumulators;
    try {
        flinkAccumulators = accumulatorSnapshot.deserializeFlinkAccumulators();
        userAccumulators = accumulatorSnapshot.deserializeUserAccumulators(userClassLoader);

        ExecutionAttemptID execID = accumulatorSnapshot.getExecutionAttemptID();
        Execution execution = currentExecutions.get(execID);
        if (execution != null) {
            execution.setAccumulators(flinkAccumulators, userAccumulators);
        }
    }
}
复制代码

对于execution,只要状态不是结束,就直接更新

复制代码
/**
 * Update accumulators (discarded when the Execution has already been terminated).
 * @param flinkAccumulators the flink internal accumulators
 * @param userAccumulators the user accumulators
 */
public void setAccumulators(Map<AccumulatorRegistry.Metric, Accumulator<?, ?>> flinkAccumulators,
                            Map<String, Accumulator<?, ?>> userAccumulators) {
    synchronized (accumulatorLock) {
        if (!state.isTerminal()) {
            this.flinkAccumulators = flinkAccumulators;
            this.userAccumulators = userAccumulators;
        }
    }
}
复制代码

 

再看TaskManager如何更新accumulator,并发送heartbeat,

复制代码
 /**
   * Sends a heartbeat message to the JobManager (if connected) with the current
   * metrics report.
   */
  protected def sendHeartbeatToJobManager(): Unit = {
    try {
      val metricsReport: Array[Byte] = metricRegistryMapper.writeValueAsBytes(metricRegistry)

      val accumulatorEvents =
        scala.collection.mutable.Buffer[AccumulatorSnapshot]()

      runningTasks foreach {
        case (execID, task) =>
          val registry = task.getAccumulatorRegistry
          val accumulators = registry.getSnapshot
          accumulatorEvents.append(accumulators)
      }

       currentJobManager foreach {
        jm => jm ! decorateMessage(Heartbeat(instanceID, metricsReport, accumulatorEvents))
      }
    }
  }
复制代码

可以看到会把每个running task的accumulators放到accumulatorEvents,然后通过Heartbeat消息发出

 

而task的accumlators是通过,task.getAccumulatorRegistry.getSnapshot得到

看看
AccumulatorRegistry
复制代码
/**
 * Main accumulator registry which encapsulates internal and user-defined accumulators.
 */
public class AccumulatorRegistry {

    protected static final Logger LOG = LoggerFactory.getLogger(AccumulatorRegistry.class);

    protected final JobID jobID;  //accumulators所属的Job
    protected final ExecutionAttemptID taskID; //taskID

    /* Flink's internal Accumulator values stored for the executing task. */
    private final Map<Metric, Accumulator<?, ?>> flinkAccumulators =   //内部的Accumulators
            new HashMap<Metric, Accumulator<?, ?>>();

    /* User-defined Accumulator values stored for the executing task. */
    private final Map<String, Accumulator<?, ?>> userAccumulators = new HashMap<>(); //用户定义的Accumulators

    /* The reporter reference that is handed to the reporting tasks. */
    private final ReadWriteReporter reporter; 
    
    /**
     * Creates a snapshot of this accumulator registry.
     * @return a serialized accumulator map
     */
    public AccumulatorSnapshot getSnapshot() {
        try {
            return new AccumulatorSnapshot(jobID, taskID, flinkAccumulators, userAccumulators);
        } catch (IOException e) {
            LOG.warn("Failed to serialize accumulators for task.", e);
            return null;
        }
    }
}
复制代码

snapshot的逻辑也很简单,

复制代码
public AccumulatorSnapshot(JobID jobID, ExecutionAttemptID executionAttemptID,
                        Map<AccumulatorRegistry.Metric, Accumulator<?, ?>> flinkAccumulators,
                        Map<String, Accumulator<?, ?>> userAccumulators) throws IOException {
    this.jobID = jobID;
    this.executionAttemptID = executionAttemptID;
    this.flinkAccumulators = new SerializedValue<Map<AccumulatorRegistry.Metric, Accumulator<?, ?>>>(flinkAccumulators);
    this.userAccumulators = new SerializedValue<Map<String, Accumulator<?, ?>>>(userAccumulators);
}
复制代码

 

最后,我们如何将统计数据累加到Accumulator上的?

直接看看Flink内部的Accumulator是如何更新的,都是通过这个reporter来更新的

复制代码
/**
 * Accumulator based reporter for keeping track of internal metrics (e.g. bytes and records in/out)
 */
private static class ReadWriteReporter implements Reporter {

    private LongCounter numRecordsIn = new LongCounter();
    private LongCounter numRecordsOut = new LongCounter();
    private LongCounter numBytesIn = new LongCounter();
    private LongCounter numBytesOut = new LongCounter();

    private ReadWriteReporter(Map<Metric, Accumulator<?,?>> accumulatorMap) {
        accumulatorMap.put(Metric.NUM_RECORDS_IN, numRecordsIn);
        accumulatorMap.put(Metric.NUM_RECORDS_OUT, numRecordsOut);
        accumulatorMap.put(Metric.NUM_BYTES_IN, numBytesIn);
        accumulatorMap.put(Metric.NUM_BYTES_OUT, numBytesOut);
    }

    @Override
    public void reportNumRecordsIn(long value) {
        numRecordsIn.add(value);
    }

    @Override
    public void reportNumRecordsOut(long value) {
        numRecordsOut.add(value);
    }

    @Override
    public void reportNumBytesIn(long value) {
        numBytesIn.add(value);
    }

    @Override
    public void reportNumBytesOut(long value) {
        numBytesOut.add(value);
    }
}
复制代码

 

何处调用到这个report的接口,

对于in, 在反序列化到record的时候会统计Bytesin和Recordsin

AdaptiveSpanningRecordDeserializer
复制代码
public DeserializationResult getNextRecord(T target) throws IOException {
    // check if we can get a full length;
    if (nonSpanningRemaining >= 4) {
        int len = this.nonSpanningWrapper.readInt();

        if (reporter != null) {
            reporter.reportNumBytesIn(len);
        }
        
        if (len <= nonSpanningRemaining - 4) {
            // we can get a full record from here
            target.read(this.nonSpanningWrapper);

            if (reporter != null) {
                reporter.reportNumRecordsIn(1);
            }
复制代码

 

所以对于out,反之则序列化的时候写入

SpanningRecordSerializer
复制代码
@Override
public SerializationResult addRecord(T record) throws IOException {
    int len = this.serializationBuffer.length();
    this.lengthBuffer.putInt(0, len);

    if (reporter != null) {
        reporter.reportNumBytesOut(len);
        reporter.reportNumRecordsOut(1);
    }
复制代码

 

使用accumulator时,需要首先extends RichFunction by callinggetRuntimeContext().addAccumulator

相关实践学习
基于Hologres轻松玩转一站式实时仓库
本场景介绍如何利用阿里云MaxCompute、实时计算Flink和交互式分析服务Hologres开发离线、实时数据融合分析的数据大屏应用。
Linux入门到精通
本套课程是从入门开始的Linux学习课程,适合初学者阅读。由浅入深案例丰富,通俗易懂。主要涉及基础的系统操作以及工作中常用的各种服务软件的应用、部署和优化。即使是零基础的学员,只要能够坚持把所有章节都学完,也一定会受益匪浅。
相关文章
|
2月前
|
运维 数据处理 数据安全/隐私保护
阿里云实时计算Flink版测评报告
该测评报告详细介绍了阿里云实时计算Flink版在用户行为分析与标签画像中的应用实践,展示了其毫秒级的数据处理能力和高效的开发流程。报告还全面评测了该服务在稳定性、性能、开发运维及安全性方面的卓越表现,并对比自建Flink集群的优势。最后,报告评估了其成本效益,强调了其灵活扩展性和高投资回报率,适合各类实时数据处理需求。
|
4月前
|
存储 监控 大数据
阿里云实时计算Flink在多行业的应用和实践
本文整理自 Flink Forward Asia 2023 中闭门会的分享。主要分享实时计算在各行业的应用实践,对回归实时计算的重点场景进行介绍以及企业如何使用实时计算技术,并且提供一些在技术架构上的参考建议。
821 7
阿里云实时计算Flink在多行业的应用和实践
|
18天前
|
存储 分布式计算 流计算
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
本文介绍了阿里云开源大数据团队在实时计算领域的最新成果——向量化流计算引擎Flash。文章主要内容包括:Apache Flink 成为业界流计算标准、Flash 核心技术解读、性能测试数据以及在阿里巴巴集团的落地效果。Flash 是一款完全兼容 Apache Flink 的新一代流计算引擎,通过向量化技术和 C++ 实现,大幅提升了性能和成本效益。
703 10
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
|
3月前
|
SQL 消息中间件 Kafka
实时计算 Flink版产品使用问题之如何在EMR-Flink的Flink SOL中针对source表单独设置并行度
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
|
15天前
|
SQL 运维 数据可视化
阿里云实时计算Flink版产品体验测评
阿里云实时计算Flink基于Apache Flink构建,提供一站式实时大数据分析平台,支持端到端亚秒级实时数据分析,适用于实时大屏、实时报表、实时ETL和风控监测等场景,具备高性价比、开发效率、运维管理和企业安全等优势。
zdl
|
6天前
|
消息中间件 运维 大数据
大数据实时计算产品的对比测评:实时计算Flink版 VS 自建Flink集群
本文介绍了实时计算Flink版与自建Flink集群的对比,涵盖部署成本、性能表现、易用性和企业级能力等方面。实时计算Flink版作为全托管服务,显著降低了运维成本,提供了强大的集成能力和弹性扩展,特别适合中小型团队和业务波动大的场景。文中还提出了改进建议,并探讨了与其他产品的联动可能性。总结指出,实时计算Flink版在简化运维、降低成本和提升易用性方面表现出色,是大数据实时计算的优选方案。
zdl
27 0
|
1月前
|
运维 搜索推荐 数据安全/隐私保护
阿里云实时计算Flink版测评报告
阿里云实时计算Flink版在用户行为分析与标签画像场景中表现出色,通过实时处理电商平台用户行为数据,生成用户兴趣偏好和标签,提升推荐系统效率。该服务具备高稳定性、低延迟、高吞吐量,支持按需计费,显著降低运维成本,提高开发效率。
67 1
|
1月前
|
运维 数据处理 Apache
数据实时计算产品对比测评报告:阿里云实时计算Flink版
数据实时计算产品对比测评报告:阿里云实时计算Flink版
|
2月前
|
存储 运维 监控
阿里云实时计算Flink版的评测
阿里云实时计算Flink版的评测
76 15
|
1月前
|
运维 监控 Serverless
阿里云实时计算Flink版评测报告
阿里云实时计算Flink版是一款全托管的Serverless实时流处理服务,基于Apache Flink构建,提供企业级增值功能。本文从稳定性、性能、开发运维、安全性和成本效益等方面全面评测该产品,展示其在实时数据处理中的卓越表现和高投资回报率。