CreateCollection API执行流程(addCollectionMetaStep)_milvus源码解析

简介: CreateCollection API执行流程(addCollectionMetaStep)_milvus源码解析

CreateCollection API执行流程(addCollectionMetaStep)源码解析

milvus版本:v2.3.2

CreateCollection这个API流程较长,也是milvus的核心API之一,涉及的内容比较复杂。这里介绍和channel相关的流程。

整体架构:

architecture.png

CreateCollection(addCollectionMetaStep)的数据流向:

watchChannelstep数据流.jpg

1.客户端sdk发出CreateCollection API请求。

from pymilvus import (
    connections,
    FieldSchema, CollectionSchema, DataType,
    Collection,
)

num_entities, dim = 3000, 1024

print("start connecting to Milvus")
connections.connect("default", host="192.168.230.71", port="19530")

fields = [
    FieldSchema(name="pk", dtype=DataType.VARCHAR, is_primary=True, auto_id=False, max_length=100),
    FieldSchema(name="random", dtype=DataType.DOUBLE),
    FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=dim)
]

schema = CollectionSchema(fields, "hello_milvus is the simplest demo to introduce the APIs")

print("Create collection `hello_milvus`")
hello_milvus = Collection("hello_milvus", schema, consistency_level="Strong",shards_num=2)

客户端SDK向proxy发送一个CreateCollection API请求,创建一个名为hello_milvus的collection。

hello_milvus.jpg

2.客户端接受API请求,将request封装为createCollectionTask,并压入ddQueue队列。

代码路径:internal\proxy\impl.go

func (node *Proxy) CreateCollection(ctx context.Context, request *milvuspb.CreateCollectionRequest) (*commonpb.Status, error) {
   
   
    ......
    // request封装为task
    cct := &createCollectionTask{
   
   
        ctx:                     ctx,
        Condition:               NewTaskCondition(ctx),
        CreateCollectionRequest: request,
        rootCoord:               node.rootCoord,
    }

    ......
    // 将task压入ddQueue队列
    if err := node.sched.ddQueue.Enqueue(cct); err != nil {
   
   
        ......
    }

    ......
    // 等待cct执行完
    if err := cct.WaitToFinish(); err != nil {
   
   
        ......
    }

    ......
}

3.执行createCollectionTask的3个方法PreExecute、Execute、PostExecute。

PreExecute()一般为参数校验等工作。

Execute()一般为真正执行逻辑。

PostExecute()执行完后的逻辑,什么都不做,返回nil。

代码路径:internal\proxy\task.go

func (t *createCollectionTask) Execute(ctx context.Context) error {
   
   
    var err error
    t.result, err = t.rootCoord.CreateCollection(ctx, t.CreateCollectionRequest)
    return err
}

从代码可以看出调用了rootCoord的CreateCollection接口。

4.进入rootCoord的CreateCollection接口。

代码路径:internal\rootcoord\root_coord.go

继续将请求封装为rootcoord里的createCollectionTask

func (c *Core) CreateCollection(ctx context.Context, in *milvuspb.CreateCollectionRequest) (*commonpb.Status, error) {
   
   
    ......
    // 封装为createCollectionTask
    t := &createCollectionTask{
   
   
        baseTask: newBaseTask(ctx, c),
        Req:      in,
    }
    // 加入调度
    if err := c.scheduler.AddTask(t); err != nil {
   
   
        ......
    }
    // 等待task完成
    if err := t.WaitToFinish(); err != nil {
   
   
        ......
    }

    ......
}

5.执行createCollectionTask的Prepare、Execute、NotifyDone方法。

Execute()为核心方法。

代码路径:internal\rootcoord\create_collection_task.go

func (t *createCollectionTask) Execute(ctx context.Context) error {
   
   
    // collID为collectionID,在Prepare()里分配
    // partIDs为partitionID,在Prepare()里分配
    collID := t.collID
    partIDs := t.partIDs
    // 产生时间戳
    ts, err := t.getCreateTs()
    if err != nil {
   
   
        return err
    }
    // vchanNames为虚拟channel,在Prepare()里分配
    // chanNames为物理channel,在Prepare()里分配
    vchanNames := t.channels.virtualChannels
    chanNames := t.channels.physicalChannels

    startPositions, err := t.addChannelsAndGetStartPositions(ctx, ts)
    if err != nil {
   
   
        t.core.chanTimeTick.removeDmlChannels(t.channels.physicalChannels...)
        return err
    }
    // 填充partition,创建collection的时候,默认只有一个名为"Default partition"的partition。
    partitions := make([]*model.Partition, len(partIDs))
    for i, partID := range partIDs {
   
   
        partitions[i] = &model.Partition{
   
   
            PartitionID:               partID,
            PartitionName:             t.partitionNames[i],
            PartitionCreatedTimestamp: ts,
            CollectionID:              collID,
            State:                     pb.PartitionState_PartitionCreated,
        }
    }
    // 填充collection
    // 可以看出collection由collID、dbid、schemaName、fields、vchanName、chanName、partition、shardNum等组成
    collInfo := model.Collection{
   
   
        CollectionID:         collID,
        DBID:                 t.dbID,
        Name:                 t.schema.Name,
        Description:          t.schema.Description,
        AutoID:               t.schema.AutoID,
        Fields:               model.UnmarshalFieldModels(t.schema.Fields),
        VirtualChannelNames:  vchanNames,
        PhysicalChannelNames: chanNames,
        ShardsNum:            t.Req.ShardsNum,
        ConsistencyLevel:     t.Req.ConsistencyLevel,
        StartPositions:       toKeyDataPairs(startPositions),
        CreateTime:           ts,
        State:                pb.CollectionState_CollectionCreating,
        Partitions:           partitions,
        Properties:           t.Req.Properties,
        EnableDynamicField:   t.schema.EnableDynamicField,
    }

    clone := collInfo.Clone()

    existedCollInfo, err := t.core.meta.GetCollectionByName(ctx, t.Req.GetDbName(), t.Req.GetCollectionName(), typeutil.MaxTimestamp)
    if err == nil {
   
   
        equal := existedCollInfo.Equal(*clone)
        if !equal {
   
   
            return fmt.Errorf("create duplicate collection with different parameters, collection: %s", t.Req.GetCollectionName())
        }

        log.Warn("add duplicate collection", zap.String("collection", t.Req.GetCollectionName()), zap.Uint64("ts", ts))
        return nil
    }
    // 分为多个step执行,每一个undoTask由todoStep和undoStep构成
    // 执行todoStep,报错则执行undoStep
    undoTask := newBaseUndoTask(t.core.stepExecutor)
    undoTask.AddStep(&expireCacheStep{
   
   
        baseStep:        baseStep{
   
   core: t.core},
        dbName:          t.Req.GetDbName(),
        collectionNames: []string{
   
   t.Req.GetCollectionName()},
        collectionID:    InvalidCollectionID,
        ts:              ts,
    }, &nullStep{
   
   })
    undoTask.AddStep(&nullStep{
   
   }, &removeDmlChannelsStep{
   
   
        baseStep:  baseStep{
   
   core: t.core},
        pChannels: chanNames,
    }) 
    undoTask.AddStep(&addCollectionMetaStep{
   
   
        baseStep: baseStep{
   
   core: t.core},
        coll:     &collInfo,
    }, &deleteCollectionMetaStep{
   
   
        baseStep:     baseStep{
   
   core: t.core},
        collectionID: collID,
        ts: ts,
    })

    undoTask.AddStep(&nullStep{
   
   }, &unwatchChannelsStep{
   
   
        baseStep:     baseStep{
   
   core: t.core},
        collectionID: collID,
        channels:     t.channels,
        isSkip:       !Params.CommonCfg.TTMsgEnabled.GetAsBool(),
    })
    undoTask.AddStep(&watchChannelsStep{
   
   
        baseStep: baseStep{
   
   core: t.core},
        info: &watchInfo{
   
   
            ts:             ts,
            collectionID:   collID,
            vChannels:      t.channels.virtualChannels,
            startPositions: toKeyDataPairs(startPositions),
            schema: &schemapb.CollectionSchema{
   
   
                Name:        collInfo.Name,
                Description: collInfo.Description,
                AutoID:      collInfo.AutoID,
                Fields:      model.MarshalFieldModels(collInfo.Fields),
            },
        },
    }, &nullStep{
   
   })
    undoTask.AddStep(&changeCollectionStateStep{
   
   
        baseStep:     baseStep{
   
   core: t.core},
        collectionID: collID,
        state:        pb.CollectionState_CollectionCreated,
        ts:           ts,
    }, &nullStep{
   
   })

    return undoTask.Execute(ctx)
}

创建collection涉及多个步骤,可以看出这里依次分为expireCacheStep、addCollectionMetaStep、watchChannelsStep、changeCollectionStateStep这几个步骤,addCollectionMetaStep是关于etcd元数据的step,已在另一篇文章对其进行详细解析。本篇幅对watchChannelsStep进行解析。

6.进入watchChannelsStep,执行其Execute()方法。

代码路径:internal\rootcoord\step.go

func (s *watchChannelsStep) Execute(ctx context.Context) ([]nestedStep, error) {
   
   
    err := s.core.broker.WatchChannels(ctx, s.info)
    return nil, err
}

在这里重点研究s.core.broker.WatchChannels()这个方法做了什么事情。

调用栈如下:

s.core.broker.WatchChannels()
  |--WatchChannels()(internal\rootcoord\broker.go)
    |--b.s.dataCoord.WatchChannels()
      |--WatchChannels()(internal\datacoord\services.go)
        |--s.channelManager.Watch()
          |--c.updateWithTimer()(internal\datacoord\channel_manager.go)
            |--c.store.Update()
              |--c.update()(internal\datacoord\channel_store.go)
                |--c.txn()(同上)
                  |--c.store.MultiSaveAndRemove()(同上)
                    |--MultiSaveAndRemove()(internal\kv\etcd\etcd_kv.go)
        |--s.meta.catalog.MarkChannelAdded()

watch_channel堆栈.jpg

WatchChannels这个操作最终是在etcd写入kv。那么我们研究写入的kv是什么。

根据堆栈顺序来进行分析。

1.WatchChannels()方法

代码路径:internal\datacoord\services.go

// WatchChannels notifies DataCoord to watch vchannels of a collection.
func (s *Server) WatchChannels(ctx context.Context, req *datapb.WatchChannelsRequest) (*datapb.WatchChannelsResponse, error) {
   
   
    log := log.Ctx(ctx).With(
        zap.Int64("collectionID", req.GetCollectionID()),
        zap.Strings("channels", req.GetChannelNames()),
    )
    log.Info("receive watch channels request")
    resp := &datapb.WatchChannelsResponse{
   
   
        Status: merr.Success(),
    }

    if err := merr.CheckHealthy(s.GetStateCode()); err != nil {
   
   
        return &datapb.WatchChannelsResponse{
   
   
            Status: merr.Status(err),
        }, nil
    }
    // req.GetChannelNames()得到的值为:
    // by-dev-rootcoord-dml_2_445674962009727985v0
    // by-dev-rootcoord-dml_3_445674962009727985v1
    for _, channelName := range req.GetChannelNames() {
   
   
        ch := &channel{
   
   
            Name:            channelName,
            CollectionID:    req.GetCollectionID(),
            StartPositions:  req.GetStartPositions(),
            Schema:          req.GetSchema(),
            CreateTimestamp: req.GetCreateTimestamp(),
        }
        // 循环执行watch()
        err := s.channelManager.Watch(ctx, ch)
        if err != nil {
   
   
            log.Warn("fail to watch channelName", zap.Error(err))
            resp.Status = merr.Status(err)
            return resp, nil
        }
        // 向etcd写入另外一个kv
        if err := s.meta.catalog.MarkChannelAdded(ctx, ch.Name); err != nil {
   
   
            // TODO: add background task to periodically cleanup the orphaned channel add marks.
            log.Error("failed to mark channel added", zap.Error(err))
            resp.Status = merr.Status(err)
            return resp, nil
        }
    }

    return resp, nil
}

函数入参req的值如下:

req值.jpg

在这里有2个channelName,是虚拟channel,为什么是2个channel?因为客户端SDK创建collection传入了shards_num=2。一个shard对应一个虚拟channel。

channel名称by-dev-rootcoord-dml_2_445674962009727985v0中的445674962009727985是collectionID。

2.进入到s.channelManager.Watch()

代码路径:internal\datacoord\channel_manager.go

// Watch tries to add the channel to cluster. Watch is a no op if the channel already exists.
func (c *ChannelManager) Watch(ctx context.Context, ch *channel) error {
   
   
    log := log.Ctx(ctx)
    c.mu.Lock()
    defer c.mu.Unlock()
    // 使用分配策略:datacoord.AverageAssignPolicy
    updates := c.assignPolicy(c.store, []*channel{
   
   ch})
    if len(updates) == 0 {
   
   
        return nil
    }
    log.Info("try to update channel watch info with ToWatch state",
        zap.String("channel", ch.String()),
        zap.Array("updates", updates))
    // 操作etcd
    err := c.updateWithTimer(updates, datapb.ChannelWatchState_ToWatch)
    if err != nil {
   
   
        log.Warn("fail to update channel watch info with ToWatch state",
            zap.String("channel", ch.String()), zap.Array("updates", updates), zap.Error(err))
    }
    return err
}

updates的值为:

updates.jpg

updates变量是一个ChannelOpSet类型。这时候ChannelWatchInfos为空。

type ChannelOpSet []*ChannelOp

type ChannelOp struct {
   
   
    Type              ChannelOpType
    NodeID            int64
    Channels          []*channel
    ChannelWatchInfos []*datapb.ChannelWatchInfo
}

3.进入c.updateWithTimer()

代码路径:internal\datacoord\channel_manager.go

func (c *ChannelManager) updateWithTimer(updates ChannelOpSet, state datapb.ChannelWatchState) error {
   
   
    channelsWithTimer := []string{
   
   }
    // updates此时数组长度为1
    for _, op := range updates {
   
   
        if op.Type == Add {
   
   
            // 填充ChannelWatchInfos
            channelsWithTimer = append(channelsWithTimer, c.fillChannelWatchInfoWithState(op, state)...)
        }
    }
    // 操作etcd
    err := c.store.Update(updates)
    if err != nil {
   
   
        log.Warn("fail to update", zap.Array("updates", updates), zap.Error(err))
        c.stateTimer.removeTimers(channelsWithTimer)
    }
    c.lastActiveTimestamp = time.Now()
    return err
}

4.进入c.store.Update()

代码路径:internal\datacoord\channel_store.go

// Update applies the channel operations in opSet.
func (c *ChannelStore) Update(opSet ChannelOpSet) error {
   
   
    totalChannelNum := 0
    for _, op := range opSet {
   
   
        totalChannelNum += len(op.Channels)
    }
    // totalChannelNum = 1
    // maxOperationsPerTxn = 64
    if totalChannelNum <= maxOperationsPerTxn {
   
   
        // 走这条路径
        return c.update(opSet)
    }
    // 如果超过则分批执行
    ......
}

5.进入c.update(opSet)

代码路径:internal\datacoord\channel_store.go

// update applies the ADD/DELETE operations to the current channel store.
func (c *ChannelStore) update(opSet ChannelOpSet) error {
   
   
    // Update ChannelStore's kv store.
    // 操作etcd
    if err := c.txn(opSet); err != nil {
   
   
        return err
    }

    // Update node id -> channel mapping.
    for _, op := range opSet {
   
   
        switch op.Type {
   
   
        case Add:
            for _, ch := range op.Channels {
   
   
                if c.checkIfExist(op.NodeID, ch) {
   
   
                    continue // prevent adding duplicated channel info
                }
                // Append target channels to channel store.
                c.channelsInfo[op.NodeID].Channels = append(c.channelsInfo[op.NodeID].Channels, ch)
            }
        case Delete:
            // Remove target channels from channel store.
            del := make(map[string]struct{
   
   })
            for _, ch := range op.Channels {
   
   
                del[ch.Name] = struct{
   
   }{
   
   }
            }
            prev := c.channelsInfo[op.NodeID].Channels
            curr := make([]*channel, 0, len(prev))
            for _, ch := range prev {
   
   
                if _, ok := del[ch.Name]; !ok {
   
   
                    curr = append(curr, ch)
                }
            }
            c.channelsInfo[op.NodeID].Channels = curr
        default:
            return errUnknownOpType
        }
        metrics.DataCoordDmlChannelNum.WithLabelValues(strconv.FormatInt(op.NodeID, 10)).Set(float64(len(c.channelsInfo[op.NodeID].Channels)))
    }
    return nil
}

6.进入c.txn(opSet)

代码路径:internal\datacoord\channel_store.go

// txn updates the channelStore's kv store with the given channel ops.
func (c *ChannelStore) txn(opSet ChannelOpSet) error {
   
   
    saves := make(map[string]string)
    var removals []string
    for _, op := range opSet {
   
   
        for i, ch := range op.Channels {
   
   
            // 构建key的规则
            k := buildNodeChannelKey(op.NodeID, ch.Name)
            switch op.Type {
   
   
            case Add:
                // 构建value,ChannelWatchInfo
                info, err := proto.Marshal(op.ChannelWatchInfos[i])
                if err != nil {
   
   
                    return err
                }
                saves[k] = string(info)
            case Delete:
                removals = append(removals, k)
            default:
                return errUnknownOpType
            }
        }
    }
    return c.store.MultiSaveAndRemove(saves, removals)
}

因为op.Type是Add,所以removals是nil。

key的值:

channelwatch/1/by-dev-rootcoord-dml_2_445674962009727985v0

规则为:channelwatch/{nodeID}/{chName}

saves变量的值:

saves.jpg

后面已经不用再跟踪下去。

使用etcd-manager查看etcd。

channelwatch.jpg

7.进入s.meta.catalog.MarkChannelAdded()

代码路径:internal\metastore\kv\datacoord\kv_catalog.go

func (kc *Catalog) MarkChannelAdded(ctx context.Context, channel string) error {
   
   
    // 构建key的规则:datacoord-meta/channel-removal/{channelName}
    key := buildChannelRemovePath(channel)
    // 构建value:NonRemoveFlagTomestone = "non-removed"
    err := kc.MetaKv.Save(key, NonRemoveFlagTomestone)
    if err != nil {
   
   
        log.Error("failed to mark channel added", zap.String("channel", channel), zap.Error(err))
        return err
    }
    log.Info("NON remove flag tombstone added", zap.String("channel", channel))
    return nil
}

构建key的规则:

datacoord-meta/channel-removal/{channelName}

channel-removal.jpg

总结:

1.CreateCollection的addCollectionMetaStep会创建2种类型的key。

  • channelwatch/{nodeID}/{chName}
  • datacoord-meta/channel-removal/{channelName}
目录
相关文章
|
2天前
|
算法 Linux 调度
xenomai内核解析--xenomai与普通linux进程之间通讯XDDP(一)--实时端socket创建流程
xenomai与普通linux进程之间通讯XDDP(一)--实时端socket创建流程
7 1
xenomai内核解析--xenomai与普通linux进程之间通讯XDDP(一)--实时端socket创建流程
|
2天前
|
Linux 调度 数据库
|
2天前
|
Linux API 调度
xenomai内核解析-xenomai实时线程创建流程
本文介绍了linux硬实时操作系统xenomai pthread_creta()接口的底层实现原理,解释了如何在双内核间创建和调度一个xenomai任务。本文是基于源代码的分析,提供了详细的流程和注释,同时给出了结论部分,方便读者快速了解核心内容。
6 0
xenomai内核解析-xenomai实时线程创建流程
|
3天前
|
供应链 监控 安全
全面剖析:新页ERP系统不为人知的一面,以及系统的工作流程解析!
全面剖析:新页ERP系统不为人知的一面,以及系统的工作流程解析!
|
4天前
|
供应链 搜索推荐 API
API在电子商务中的应用与优势:深入解析
API是电子商务成功的关键,它们不仅促进了技术创新,还提高了用户体验和运营效率。随着技术的不断进步,API将继续在电子商务领域发挥更加重要的作用。电子商务平台通过利用API,可以更加灵活地适应市场变化,提供更加丰富和个性化的购物体验,最终实现业务的增长和扩展。
|
12天前
|
缓存 Java 开发者
10个点介绍SpringBoot3工作流程与核心组件源码解析
Spring Boot 是Java开发中100%会使用到的框架,开发者不仅要熟练使用,对其中的核心源码也要了解,正所谓知其然知其所以然,V 哥建议小伙伴们在学习的过程中,一定要去研读一下源码,这有助于你在开发中游刃有余。欢迎一起交流学习心得,一起成长。
|
17天前
|
SQL 关系型数据库 API
从API获取数据并将其插入到PostgreSQL数据库:步骤解析
使用Python处理从API获取的数据并插入到PostgreSQL数据库:安装`psycopg2`,建立数据库连接,确保DataFrame与表结构匹配,然后使用`to_sql`方法将数据插入到已存在的表中。注意数据准备、权限设置、性能优化和安全处理。
|
23小时前
|
安全 API 开发者
智能体-Agent能力升级!新增Assistant API & Tools API服务接口
ModelScope-Agent是一个交互式创作空间,它支持LLM(Language Model)的扩展能力,例如工具调用(function calling)和知识检索(knowledge retrieval)。它已经对相关接口进行了开源,以提供更原子化的应用LLM能力。用户可以通过Modelscope-Agent上的不同代理(agent),结合自定义的LLM配置和消息,调用这些能力。
|
5天前
|
JSON 搜索推荐 数据挖掘
电商数据分析的利器:电商关键词搜索API接口(标题丨图片丨价格丨链接)
淘宝关键词搜索接口为电商领域的数据分析提供了丰富的数据源。通过有效利用这一接口,企业和研究人员可以更深入地洞察市场动态,优化营销策略,并提升用户体验。随着电商平台技术的不断进步,未来的API将更加智能和个性化,为电商行业带来更多的可能性。
|
12天前
|
存储 缓存 运维
DataWorks操作报错合集之DataWorks根据api,调用查询文件列表接口报错如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
23 1

推荐镜像

更多