roman_日积跬步-终至千里

roman_日积跬步-终至千里

一.ManagedMemory(算子)内存的申请与使用

1. tm内存申请与使用大致流程

Task使用的物理计算资源主要是TaskSlot提供的,TaskSlot由TaskManager中TaskSlotTable组件创建和管理。

 

2. 创建MemoryManager实例

在TaskSlot的构造器中调用createMemoryManager()方法创建MemoryManager实例,管理当前TaskSlot(代表一个线程的资源) 中的内存空间

/**
创建具有**给定**容量和给定页面大小的内存管理器。
这是 MemoryManager 的生产版本,一旦 MemoryManager 
的所有者准备好处置,它就会检查内存泄漏 ( verifyEmpty() )。

参数:
memorySize – 该内存管理器管理的堆外内存的总大小。 
pageSize – 内存管理器分配的页面大小。
**/
private static MemoryManager createMemoryManager(  
        ResourceProfile resourceProfile, int pageSize) {  
    return MemoryManager.create(resourceProfile.getManagedMemory().getBytes(), pageSize);  
}

在TaskSlot.createMemoryManager()方法中,会根据ResourceProfile参数获取内存空间大小,默认设置为非堆ing。其中pageSize参数就是MemorySegment的大小,如下代码默认为32kb。

TaskManagerOptions.
@Documentation.Section(Documentation.Sections.ALL_TASK_MANAGER)  
public static final ConfigOption<MemorySize> MEMORY_SEGMENT_SIZE =  
        key("taskmanager.memory.segment-size")  
                .memoryType()  
                .defaultValue(MemorySize.parse("32kb"))  
                .withDescription(  
                        "Size of memory buffers used by the network stack and the memory manager.");
                    

 

3. 算子使用通过MemoryManager使用内存

MemoryManager创建完毕后,会通过TaskSlot将MemoryManager对象传递给Task,此时Task会通过将MemoryManager封装在Environment变量中,然后传递给算子
算子接收到MemoryManager对象后,通过MemoryManager动态申请内存空间,最终用于算子的具体计算过程。

 

4. ManagedMemory内存空间申请流程

申请ManagedMemory内存空间,是调用MemoryManager.allocatePages()方法执行的,见如下逻辑。

/**
从此内存管理器分配一组内存段。
分配的总内存不会超过构造函数中声明的大小限制。
参数:
owner – 与内存段关联的所有者,用于后备释放。 
target – 将分配的内存页放入其中的列表。 numberOfPages – 要分配的页数。
**/
public void allocatePages(Object owner, Collection<MemorySegment> target, int numberOfPages)  
        throws MemoryAllocationException {  
    // sanity check  
    Preconditions.checkNotNull(owner, "The memory owner must not be null.");  
    Preconditions.checkState(!isShutDown, "Memory manager has been shut down.");  
    Preconditions.checkArgument(  
            numberOfPages <= totalNumberOfPages,  
            "Cannot allocate more segments %s than the max number %s",  
            numberOfPages,  
            totalNumberOfPages);  
  
    // reserve array space, if applicable  
    if (target instanceof ArrayList) {  
        ((ArrayList<MemorySegment>) target).ensureCapacity(numberOfPages);  
    }  
    //计算申请内存大小,并预留空间(以免申请过程中被用掉)
    long memoryToReserve = numberOfPages * pageSize;  
    try {  
        memoryBudget.reserveMemory(memoryToReserve);  
    } catch (MemoryReservationException e) {  
        throw new MemoryAllocationException(  
                String.format("Could not allocate %d pages", numberOfPages), e);  
    }  
    //创建pageCleanup方法用于清理unsafe内存
    Runnable pageCleanup = this::releasePage;  
    allocatedSegments.compute(  
            owner,  
            (o, currentSegmentsForOwner) -> {  
                Set<MemorySegment> segmentsForOwner =  
                        currentSegmentsForOwner == null  
                                ? new HashSet<>(numberOfPages)  
                                : currentSegmentsForOwner;  
                for (long i = numberOfPages; i > 0; i--) {  
                 //分配内存
                    MemorySegment segment =  
                            allocateOffHeapUnsafeMemory(getPageSize(), owner, pageCleanup);  
                    target.add(segment);  
                    segmentsForOwner.add(segment);  
                }  
                return segmentsForOwner;  
            });  
  
    Preconditions.checkState(!isShutDown, "Memory manager has been concurrently shut down.");  
}					

如下如下算子会申请内存使用:
flink内存管理(三):MemorySegment内存使用场景:托管内存与网络内存-LMLPHP

 

二.NetworkBuffer内存申请与使用

在Flink内存模型中,另外一个非常重要的堆外内存使用区域就是Network内存。Network内存主要用于网络传输中Buffer数据的缓冲区。

1. NetworkBuffer构造器

在NetworkBufferPool的构造器中可以看出,创建NetworkBufferPool时会根据用户配置的NetworkBuffer数量,调用MemorySegmentFactory创建相应的MemorySegment内存空间,再通过LocalBufferPool应用到ResultSubPartition或InputChannel组件中。

public NetworkBufferPool(
            int numberOfSegmentsToAllocate, int segmentSize, Duration requestSegmentsTimeout) {
        this.totalNumberOfMemorySegments = numberOfSegmentsToAllocate;
        this.memorySegmentSize = segmentSize;

        Preconditions.checkNotNull(requestSegmentsTimeout);
        checkArgument(
                requestSegmentsTimeout.toMillis() > 0,
                "The timeout for requesting exclusive buffers should be positive.");
        this.requestSegmentsTimeout = requestSegmentsTimeout;

        final long sizeInLong = (long) segmentSize;

        try {
            this.availableMemorySegments = new ArrayDeque<>(numberOfSegmentsToAllocate);
        } catch (OutOfMemoryError err) {
            throw new OutOfMemoryError(
                    "Could not allocate buffer queue of length "
                            + numberOfSegmentsToAllocate
                            + " - "
                            + err.getMessage());
        }

        try {
            //申请segment内存,并放到availableMemorySegments中。
            for (int i = 0; i < numberOfSegmentsToAllocate; i++) {
                availableMemorySegments.add(
                        MemorySegmentFactory.allocateUnpooledOffHeapMemory(segmentSize, null));
            }
        } catch (OutOfMemoryError err) {
        //如果申请过程中失败,则释放已申请的内存,算出缺少多少内存
            int allocated = availableMemorySegments.size();

            // free some memory
            availableMemorySegments.clear();

            long requiredMb = (sizeInLong * numberOfSegmentsToAllocate) >> 20;
            long allocatedMb = (sizeInLong * allocated) >> 20;
            long missingMb = requiredMb - allocatedMb;

            throw new OutOfMemoryError(
                    "Could not allocate enough memory segments for NetworkBufferPool "
                            + "(required (MB): "
                            + requiredMb
                            + ", allocated (MB): "
                            + allocatedMb
                            + ", missing (MB): "
                            + missingMb
                            + "). Cause: "
                            + err.getMessage());
        }

        availabilityHelper.resetAvailable();
        //计算共申请了多少mb:20:为2的20次方
        long allocatedMb = (sizeInLong * availableMemorySegments.size()) >> 20;

        LOG.info(
                "Allocated {} MB for network buffer pool (number of memory segments: {}, bytes per segment: {}).",
                allocatedMb,
                availableMemorySegments.size(),
                segmentSize);
    }

 
参考:《Flink设计与实现:核心原理与源码解析》- 张利兵

01-22 08:36