flink - accumulator

本文涉及的产品
实时计算 Flink 版,1000CU*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+Flink搭建GitHub实时数据大屏
通过使用Flink、Hologres构建实时数仓,并通过Hologres对接BI分析工具(以DataV为例),实现海量数据实时分析.
实时计算 Flink 实战课程
如何使用实时计算 Flink 搞定数据处理难题?实时计算 Flink 极客训练营产品、技术专家齐上阵,从开源 Flink功能介绍到实时计算 Flink 优势详解,现场实操,5天即可上手! 欢迎开通实时计算 Flink 版: https://cn.aliyun.com/product/bigdata/sc Flink Forward Asia 介绍: Flink Forward 是由 Apache 官方授权,Apache Flink Community China 支持的会议,通过参会不仅可以了解到 Flink 社区的最新动态和发展计划,还可以了解到国内外一线大厂围绕 Flink 生态的生产实践经验,是 Flink 开发者和使用者不可错过的盛会。 去年经过品牌升级后的 Flink Forward Asia 吸引了超过2000人线下参与,一举成为国内最大的 Apache 顶级项目会议。结合2020年的特殊情况,Flink Forward Asia 2020 将在12月26日以线上峰会的形式与大家见面。
相关文章
|
12月前
|
运维 数据处理 数据安全/隐私保护
阿里云实时计算Flink版测评报告
该测评报告详细介绍了阿里云实时计算Flink版在用户行为分析与标签画像中的应用实践,展示了其毫秒级的数据处理能力和高效的开发流程。报告还全面评测了该服务在稳定性、性能、开发运维及安全性方面的卓越表现,并对比自建Flink集群的优势。最后,报告评估了其成本效益,强调了其灵活扩展性和高投资回报率,适合各类实时数据处理需求。
|
存储 监控 大数据
阿里云实时计算Flink在多行业的应用和实践
本文整理自 Flink Forward Asia 2023 中闭门会的分享。主要分享实时计算在各行业的应用实践,对回归实时计算的重点场景进行介绍以及企业如何使用实时计算技术,并且提供一些在技术架构上的参考建议。
1329 7
阿里云实时计算Flink在多行业的应用和实践
|
10月前
|
存储 分布式计算 流计算
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
本文介绍了阿里云开源大数据团队在实时计算领域的最新成果——向量化流计算引擎Flash。文章主要内容包括:Apache Flink 成为业界流计算标准、Flash 核心技术解读、性能测试数据以及在阿里巴巴集团的落地效果。Flash 是一款完全兼容 Apache Flink 的新一代流计算引擎,通过向量化技术和 C++ 实现,大幅提升了性能和成本效益。
3155 73
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
zdl
|
10月前
|
消息中间件 运维 大数据
大数据实时计算产品的对比测评:实时计算Flink版 VS 自建Flink集群
本文介绍了实时计算Flink版与自建Flink集群的对比,涵盖部署成本、性能表现、易用性和企业级能力等方面。实时计算Flink版作为全托管服务,显著降低了运维成本,提供了强大的集成能力和弹性扩展,特别适合中小型团队和业务波动大的场景。文中还提出了改进建议,并探讨了与其他产品的联动可能性。总结指出,实时计算Flink版在简化运维、降低成本和提升易用性方面表现出色,是大数据实时计算的优选方案。
zdl
410 56
|
SQL 消息中间件 Kafka
实时计算 Flink版产品使用问题之如何在EMR-Flink的Flink SOL中针对source表单独设置并行度
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
|
8月前
|
消息中间件 关系型数据库 MySQL
Flink CDC 在阿里云实时计算Flink版的云上实践
本文整理自阿里云高级开发工程师阮航在Flink Forward Asia 2024的分享,重点介绍了Flink CDC与实时计算Flink的集成、CDC YAML的核心功能及应用场景。主要内容包括:Flink CDC的发展及其在流批数据处理中的作用;CDC YAML支持的同步链路、Transform和Route功能、丰富的监控指标;典型应用场景如整库同步、Binlog原始数据同步、分库分表同步等;并通过两个Demo展示了MySQL整库同步到Paimon和Binlog同步到Kafka的过程。最后,介绍了未来规划,如脏数据处理、数据限流及扩展数据源支持。
527 0
Flink CDC 在阿里云实时计算Flink版的云上实践
|
9月前
|
存储 关系型数据库 BI
实时计算UniFlow:Flink+Paimon构建流批一体实时湖仓
实时计算架构中,传统湖仓架构在数据流量管控和应用场景支持上表现良好,但在实际运营中常忽略细节,导致新问题。为解决这些问题,提出了流批一体的实时计算湖仓架构——UniFlow。该架构通过统一的流批计算引擎、存储格式(如Paimon)和Flink CDC工具,简化开发流程,降低成本,并确保数据一致性和实时性。UniFlow还引入了Flink Materialized Table,实现了声明式ETL,优化了调度和执行模式,使用户能灵活调整新鲜度与成本。最终,UniFlow不仅提高了开发和运维效率,还提供了更实时的数据支持,满足业务决策需求。
|
人工智能 Apache 流计算
Flink Forward Asia 2024 上海站|探索实时计算新边界
Flink Forward Asia 2024 即将盛大开幕!11 月 29 至 30 日在上海举行,大会聚焦 Apache Flink 技术演进与未来规划,涵盖流式湖仓、流批一体、Data+AI 融合等前沿话题,提供近百场专业演讲。立即报名,共襄盛举!官网:https://asia.flink-forward.org/shanghai-2024/
1189 33
Flink Forward Asia 2024 上海站|探索实时计算新边界
|
10月前
|
SQL 运维 数据可视化
阿里云实时计算Flink版产品体验测评
阿里云实时计算Flink基于Apache Flink构建,提供一站式实时大数据分析平台,支持端到端亚秒级实时数据分析,适用于实时大屏、实时报表、实时ETL和风控监测等场景,具备高性价比、开发效率、运维管理和企业安全等优势。

热门文章

最新文章