meta_table.go 35.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.

12
package rootcoord
13 14

import (
15
	"errors"
S
sunby 已提交
16
	"fmt"
Z
zhenshan.cao 已提交
17
	"path"
18 19 20 21
	"strconv"
	"sync"

	"github.com/golang/protobuf/proto"
B
bigsheeper 已提交
22 23
	"go.uber.org/zap"

X
Xiangyu Wang 已提交
24 25 26 27 28 29
	"github.com/milvus-io/milvus/internal/kv"
	"github.com/milvus-io/milvus/internal/log"
	"github.com/milvus-io/milvus/internal/proto/commonpb"
	"github.com/milvus-io/milvus/internal/proto/datapb"
	pb "github.com/milvus-io/milvus/internal/proto/etcdpb"
	"github.com/milvus-io/milvus/internal/proto/schemapb"
30
	"github.com/milvus-io/milvus/internal/util/typeutil"
31 32
)

Z
zhenshan.cao 已提交
33
const (
N
neza2017 已提交
34 35 36 37 38 39 40
	ComponentPrefix        = "master-service"
	TenantMetaPrefix       = ComponentPrefix + "/tenant"
	ProxyMetaPrefix        = ComponentPrefix + "/proxy"
	CollectionMetaPrefix   = ComponentPrefix + "/collection"
	PartitionMetaPrefix    = ComponentPrefix + "/partition"
	SegmentIndexMetaPrefix = ComponentPrefix + "/segment-index"
	IndexMetaPrefix        = ComponentPrefix + "/index"
41

42 43
	TimestampPrefix = ComponentPrefix + "/timestamp"

44 45 46 47
	SegInfoMsgStartPosPrefix    = ComponentPrefix + "/seg-info-msg-start-position"
	SegInfoMsgEndPosPrefix      = ComponentPrefix + "/seg-info-msg-end-position"
	FlushedSegMsgStartPosPrefix = ComponentPrefix + "/flushed-seg-msg-start-position"
	FlushedSegMsgEndPosPrefix   = ComponentPrefix + "/flushed-seg-msg-end-position"
48

49 50
	DDOperationPrefix = ComponentPrefix + "/dd-operation"
	DDMsgSendPrefix   = ComponentPrefix + "/dd-msg-send"
51

52 53 54 55
	CreateCollectionDDType = "CreateCollection"
	DropCollectionDDType   = "DropCollection"
	CreatePartitionDDType  = "CreatePartition"
	DropPartitionDDType    = "DropPartition"
Z
zhenshan.cao 已提交
56 57
)

58
type metaTable struct {
59
	client             kv.SnapShotKV                                                    // client of a reliable kv service, i.e. etcd client
N
neza2017 已提交
60 61
	tenantID2Meta      map[typeutil.UniqueID]pb.TenantMeta                              // tenant id to tenant meta
	proxyID2Meta       map[typeutil.UniqueID]pb.ProxyMeta                               // proxy id to proxy meta
N
neza2017 已提交
62
	collID2Meta        map[typeutil.UniqueID]pb.CollectionInfo                          // collection_id -> meta
N
neza2017 已提交
63
	collName2ID        map[string]typeutil.UniqueID                                     // collection name to collection id
N
neza2017 已提交
64 65 66
	partitionID2Meta   map[typeutil.UniqueID]pb.PartitionInfo                           // collection_id/partition_id -> meta
	segID2IndexMeta    map[typeutil.UniqueID]*map[typeutil.UniqueID]pb.SegmentIndexInfo // collection_id/index_id/partition_id/segment_id -> meta
	indexID2Meta       map[typeutil.UniqueID]pb.IndexInfo                               // collection_id/index_id -> meta
N
neza2017 已提交
67
	segID2CollID       map[typeutil.UniqueID]typeutil.UniqueID                          // segment id -> collection id
N
neza2017 已提交
68
	segID2PartitionID  map[typeutil.UniqueID]typeutil.UniqueID                          // segment id -> partition id
69
	flushedSegID       map[typeutil.UniqueID]bool                                       // flushed segment id
N
neza2017 已提交
70
	partitionID2CollID map[typeutil.UniqueID]typeutil.UniqueID                          // partition id -> collection id
71 72 73 74 75 76

	tenantLock sync.RWMutex
	proxyLock  sync.RWMutex
	ddLock     sync.RWMutex
}

77
func NewMetaTable(kv kv.SnapShotKV) (*metaTable, error) {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
	mt := &metaTable{
		client:     kv,
		tenantLock: sync.RWMutex{},
		proxyLock:  sync.RWMutex{},
		ddLock:     sync.RWMutex{},
	}
	err := mt.reloadFromKV()
	if err != nil {
		return nil, err
	}
	return mt, nil
}

func (mt *metaTable) reloadFromKV() error {

	mt.tenantID2Meta = make(map[typeutil.UniqueID]pb.TenantMeta)
	mt.proxyID2Meta = make(map[typeutil.UniqueID]pb.ProxyMeta)
Z
zhenshan.cao 已提交
95
	mt.collID2Meta = make(map[typeutil.UniqueID]pb.CollectionInfo)
96
	mt.collName2ID = make(map[string]typeutil.UniqueID)
Z
zhenshan.cao 已提交
97 98 99
	mt.partitionID2Meta = make(map[typeutil.UniqueID]pb.PartitionInfo)
	mt.segID2IndexMeta = make(map[typeutil.UniqueID]*map[typeutil.UniqueID]pb.SegmentIndexInfo)
	mt.indexID2Meta = make(map[typeutil.UniqueID]pb.IndexInfo)
N
neza2017 已提交
100 101
	mt.partitionID2CollID = make(map[typeutil.UniqueID]typeutil.UniqueID)
	mt.segID2CollID = make(map[typeutil.UniqueID]typeutil.UniqueID)
N
neza2017 已提交
102
	mt.segID2PartitionID = make(map[typeutil.UniqueID]typeutil.UniqueID)
103
	mt.flushedSegID = make(map[typeutil.UniqueID]bool)
104

105
	_, values, err := mt.client.LoadWithPrefix(TenantMetaPrefix, 0)
106 107 108 109 110 111 112 113
	if err != nil {
		return err
	}

	for _, value := range values {
		tenantMeta := pb.TenantMeta{}
		err := proto.UnmarshalText(value, &tenantMeta)
		if err != nil {
114
			return fmt.Errorf("MasterService UnmarshalText pb.TenantMeta err:%w", err)
115 116 117 118
		}
		mt.tenantID2Meta[tenantMeta.ID] = tenantMeta
	}

119
	_, values, err = mt.client.LoadWithPrefix(ProxyMetaPrefix, 0)
120 121 122 123 124 125 126 127
	if err != nil {
		return err
	}

	for _, value := range values {
		proxyMeta := pb.ProxyMeta{}
		err = proto.UnmarshalText(value, &proxyMeta)
		if err != nil {
128
			return fmt.Errorf("MasterService UnmarshalText pb.ProxyMeta err:%w", err)
129 130 131 132
		}
		mt.proxyID2Meta[proxyMeta.ID] = proxyMeta
	}

133
	_, values, err = mt.client.LoadWithPrefix(CollectionMetaPrefix, 0)
134 135 136 137 138
	if err != nil {
		return err
	}

	for _, value := range values {
139 140
		collInfo := pb.CollectionInfo{}
		err = proto.UnmarshalText(value, &collInfo)
141
		if err != nil {
142
			return fmt.Errorf("MasterService UnmarshalText pb.CollectionInfo err:%w", err)
143
		}
144 145 146 147 148
		mt.collID2Meta[collInfo.ID] = collInfo
		mt.collName2ID[collInfo.Schema.Name] = collInfo.ID
		for _, partID := range collInfo.PartitionIDs {
			mt.partitionID2CollID[partID] = collInfo.ID
		}
149 150
	}

151
	_, values, err = mt.client.LoadWithPrefix(PartitionMetaPrefix, 0)
152 153 154 155
	if err != nil {
		return err
	}
	for _, value := range values {
Z
zhenshan.cao 已提交
156 157
		partitionInfo := pb.PartitionInfo{}
		err = proto.UnmarshalText(value, &partitionInfo)
158
		if err != nil {
N
neza2017 已提交
159
			return fmt.Errorf("MasterService UnmarshalText pb.PartitionInfo err:%w", err)
160
		}
N
neza2017 已提交
161 162
		collID, ok := mt.partitionID2CollID[partitionInfo.PartitionID]
		if !ok {
N
neza2017 已提交
163
			log.Warn("partition does not belong to any collection", zap.Int64("partition id", partitionInfo.PartitionID))
N
neza2017 已提交
164 165
			continue
		}
Z
zhenshan.cao 已提交
166
		mt.partitionID2Meta[partitionInfo.PartitionID] = partitionInfo
N
neza2017 已提交
167 168
		for _, segID := range partitionInfo.SegmentIDs {
			mt.segID2CollID[segID] = collID
N
neza2017 已提交
169
			mt.segID2PartitionID[segID] = partitionInfo.PartitionID
170
			mt.flushedSegID[segID] = true
N
neza2017 已提交
171
		}
172 173
	}

174
	_, values, err = mt.client.LoadWithPrefix(SegmentIndexMetaPrefix, 0)
175 176 177
	if err != nil {
		return err
	}
Z
zhenshan.cao 已提交
178 179 180
	for _, value := range values {
		segmentIndexInfo := pb.SegmentIndexInfo{}
		err = proto.UnmarshalText(value, &segmentIndexInfo)
181
		if err != nil {
182
			return fmt.Errorf("MasterService UnmarshalText pb.SegmentIndexInfo err:%w", err)
183
		}
Z
zhenshan.cao 已提交
184
		idx, ok := mt.segID2IndexMeta[segmentIndexInfo.SegmentID]
185
		if ok {
Z
zhenshan.cao 已提交
186 187 188 189 190
			(*idx)[segmentIndexInfo.IndexID] = segmentIndexInfo
		} else {
			meta := make(map[typeutil.UniqueID]pb.SegmentIndexInfo)
			meta[segmentIndexInfo.IndexID] = segmentIndexInfo
			mt.segID2IndexMeta[segmentIndexInfo.SegmentID] = &meta
191 192 193
		}
	}

194
	_, values, err = mt.client.LoadWithPrefix(IndexMetaPrefix, 0)
Z
zhenshan.cao 已提交
195 196
	if err != nil {
		return err
197
	}
Z
zhenshan.cao 已提交
198 199 200 201
	for _, value := range values {
		meta := pb.IndexInfo{}
		err = proto.UnmarshalText(value, &meta)
		if err != nil {
202
			return fmt.Errorf("MasterService UnmarshalText pb.IndexInfo err:%w", err)
203
		}
Z
zhenshan.cao 已提交
204
		mt.indexID2Meta[meta.IndexID] = meta
205 206
	}

Z
zhenshan.cao 已提交
207
	return nil
208 209
}

N
neza2017 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223
func (mt *metaTable) getAdditionKV(op func(ts typeutil.Timestamp) (string, error), meta map[string]string) func(ts typeutil.Timestamp) (string, string, error) {
	if op == nil {
		return nil
	}
	meta[DDMsgSendPrefix] = "false"
	return func(ts typeutil.Timestamp) (string, string, error) {
		val, err := op(ts)
		if err != nil {
			return "", "", err
		}
		return DDOperationPrefix, val, nil
	}
}

224
func (mt *metaTable) AddTenant(te *pb.TenantMeta) (typeutil.Timestamp, error) {
N
neza2017 已提交
225 226 227 228 229 230
	mt.tenantLock.Lock()
	defer mt.tenantLock.Unlock()

	k := fmt.Sprintf("%s/%d", TenantMetaPrefix, te.ID)
	v := proto.MarshalTextString(te)

231 232 233
	ts, err := mt.client.Save(k, v)
	if err != nil {
		return 0, err
N
neza2017 已提交
234 235
	}
	mt.tenantID2Meta[te.ID] = *te
236
	return ts, nil
N
neza2017 已提交
237 238
}

239
func (mt *metaTable) AddProxy(po *pb.ProxyMeta) (typeutil.Timestamp, error) {
N
neza2017 已提交
240 241 242 243 244 245
	mt.proxyLock.Lock()
	defer mt.proxyLock.Unlock()

	k := fmt.Sprintf("%s/%d", ProxyMetaPrefix, po.ID)
	v := proto.MarshalTextString(po)

246 247 248
	ts, err := mt.client.Save(k, v)
	if err != nil {
		return 0, err
N
neza2017 已提交
249 250
	}
	mt.proxyID2Meta[po.ID] = *po
251
	return ts, nil
N
neza2017 已提交
252 253
}

N
neza2017 已提交
254
func (mt *metaTable) AddCollection(coll *pb.CollectionInfo, part *pb.PartitionInfo, idx []*pb.IndexInfo, ddOpStr func(ts typeutil.Timestamp) (string, error)) (typeutil.Timestamp, error) {
255 256
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
Z
zhenshan.cao 已提交
257 258

	if len(part.SegmentIDs) != 0 {
259
		return 0, errors.New("segment should be empty when creating collection")
260
	}
Z
zhenshan.cao 已提交
261
	if len(coll.PartitionIDs) != 0 {
262
		return 0, errors.New("partitions should be empty when creating collection")
263
	}
264
	if _, ok := mt.collName2ID[coll.Schema.Name]; ok {
265
		return 0, fmt.Errorf("collection %s exist", coll.Schema.Name)
266
	}
N
neza2017 已提交
267
	if len(coll.FieldIndexes) != len(idx) {
268
		return 0, fmt.Errorf("incorrect index id when creating collection")
N
neza2017 已提交
269
	}
N
neza2017 已提交
270 271 272
	if _, ok := mt.partitionID2Meta[part.PartitionID]; ok {
		return 0, fmt.Errorf("partition id = %d exist", part.PartitionID)
	}
273

Z
zhenshan.cao 已提交
274 275 276 277
	coll.PartitionIDs = append(coll.PartitionIDs, part.PartitionID)
	mt.collID2Meta[coll.ID] = *coll
	mt.collName2ID[coll.Schema.Name] = coll.ID
	mt.partitionID2Meta[part.PartitionID] = *part
N
neza2017 已提交
278
	mt.partitionID2CollID[part.PartitionID] = coll.ID
N
neza2017 已提交
279 280 281
	for _, i := range idx {
		mt.indexID2Meta[i.IndexID] = *i
	}
Z
zhenshan.cao 已提交
282

N
neza2017 已提交
283
	k1 := fmt.Sprintf("%s/%d", CollectionMetaPrefix, coll.ID)
Z
zhenshan.cao 已提交
284
	v1 := proto.MarshalTextString(coll)
N
neza2017 已提交
285
	k2 := fmt.Sprintf("%s/%d/%d", PartitionMetaPrefix, coll.ID, part.PartitionID)
Z
zhenshan.cao 已提交
286 287 288
	v2 := proto.MarshalTextString(part)
	meta := map[string]string{k1: v1, k2: v2}

N
neza2017 已提交
289
	for _, i := range idx {
N
neza2017 已提交
290
		k := fmt.Sprintf("%s/%d/%d", IndexMetaPrefix, coll.ID, i.IndexID)
N
neza2017 已提交
291 292 293 294
		v := proto.MarshalTextString(i)
		meta[k] = v
	}

295
	// save ddOpStr into etcd
N
neza2017 已提交
296 297
	addition := mt.getAdditionKV(ddOpStr, meta)
	ts, err := mt.client.MultiSave(meta, addition)
298 299
	if err != nil {
		_ = mt.reloadFromKV()
300
		return 0, err
301
	}
302

303
	return ts, nil
304 305
}

N
neza2017 已提交
306
func (mt *metaTable) DeleteCollection(collID typeutil.UniqueID, ddOpStr func(ts typeutil.Timestamp) (string, error)) (typeutil.Timestamp, error) {
307 308 309 310 311
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
312
		return 0, fmt.Errorf("can't find collection. id = %d", collID)
313 314
	}

Z
zhenshan.cao 已提交
315 316 317 318 319
	delete(mt.collID2Meta, collID)
	delete(mt.collName2ID, collMeta.Schema.Name)
	for _, partID := range collMeta.PartitionIDs {
		partMeta, ok := mt.partitionID2Meta[partID]
		if !ok {
N
neza2017 已提交
320
			log.Warn("partition id not exist", zap.Int64("partition id", partID))
Z
zhenshan.cao 已提交
321 322 323 324
			continue
		}
		delete(mt.partitionID2Meta, partID)
		for _, segID := range partMeta.SegmentIDs {
325 326 327
			delete(mt.segID2CollID, segID)
			delete(mt.segID2PartitionID, segID)
			delete(mt.flushedSegID, segID)
N
neza2017 已提交
328
			_, ok := mt.segID2IndexMeta[segID]
Z
zhenshan.cao 已提交
329
			if !ok {
N
neza2017 已提交
330
				log.Warn("segment id not exist", zap.Int64("segment id", segID))
Z
zhenshan.cao 已提交
331 332 333 334 335
				continue
			}
			delete(mt.segID2IndexMeta, segID)
		}
	}
N
neza2017 已提交
336 337 338 339 340 341 342 343
	for _, idxInfo := range collMeta.FieldIndexes {
		_, ok := mt.indexID2Meta[idxInfo.IndexID]
		if !ok {
			log.Warn("index id not exist", zap.Int64("index id", idxInfo.IndexID))
			continue
		}
		delete(mt.indexID2Meta, idxInfo.IndexID)
	}
344

345
	delMetakeys := []string{
N
neza2017 已提交
346 347 348 349 350
		fmt.Sprintf("%s/%d", CollectionMetaPrefix, collID),
		fmt.Sprintf("%s/%d", PartitionMetaPrefix, collID),
		fmt.Sprintf("%s/%d", SegmentIndexMetaPrefix, collID),
		fmt.Sprintf("%s/%d", IndexMetaPrefix, collID),
	}
351

352
	// save ddOpStr into etcd
N
neza2017 已提交
353 354 355
	var saveMeta = map[string]string{}
	addition := mt.getAdditionKV(ddOpStr, saveMeta)
	ts, err := mt.client.MultiSaveAndRemoveWithPrefix(saveMeta, delMetakeys, addition)
356 357
	if err != nil {
		_ = mt.reloadFromKV()
358
		return 0, err
359 360
	}

361
	return ts, nil
362 363
}

364
func (mt *metaTable) HasCollection(collID typeutil.UniqueID, ts typeutil.Timestamp) bool {
365 366
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
367 368 369 370 371 372 373
	if ts == 0 {
		_, ok := mt.collID2Meta[collID]
		return ok
	}
	key := fmt.Sprintf("%s/%d", CollectionMetaPrefix, collID)
	_, err := mt.client.Load(key, ts)
	return err == nil
374 375
}

376
func (mt *metaTable) GetCollectionByID(collectionID typeutil.UniqueID, ts typeutil.Timestamp) (*pb.CollectionInfo, error) {
N
neza2017 已提交
377 378 379
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

380 381 382 383 384 385 386
	if ts == 0 {
		col, ok := mt.collID2Meta[collectionID]
		if !ok {
			return nil, fmt.Errorf("can't find collection id : %d", collectionID)
		}
		colCopy := proto.Clone(&col)
		return colCopy.(*pb.CollectionInfo), nil
N
neza2017 已提交
387
	}
388 389 390 391 392 393 394 395 396 397 398
	key := fmt.Sprintf("%s/%d", CollectionMetaPrefix, collectionID)
	val, err := mt.client.Load(key, ts)
	if err != nil {
		return nil, err
	}
	colMeta := pb.CollectionInfo{}
	err = proto.UnmarshalText(val, &colMeta)
	if err != nil {
		return nil, err
	}
	return &colMeta, nil
N
neza2017 已提交
399 400
}

401
func (mt *metaTable) GetCollectionByName(collectionName string, ts typeutil.Timestamp) (*pb.CollectionInfo, error) {
402 403 404
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

405 406 407 408 409 410 411 412 413 414 415
	if ts == 0 {
		vid, ok := mt.collName2ID[collectionName]
		if !ok {
			return nil, fmt.Errorf("can't find collection: " + collectionName)
		}
		col, ok := mt.collID2Meta[vid]
		if !ok {
			return nil, fmt.Errorf("can't find collection: " + collectionName)
		}
		colCopy := proto.Clone(&col)
		return colCopy.(*pb.CollectionInfo), nil
N
neza2017 已提交
416
	}
417 418 419
	_, vals, err := mt.client.LoadWithPrefix(CollectionMetaPrefix, ts)
	if err != nil {
		return nil, err
N
neza2017 已提交
420
	}
421 422 423 424 425 426 427 428 429 430 431 432
	for _, val := range vals {
		collMeta := pb.CollectionInfo{}
		err = proto.UnmarshalText(val, &collMeta)
		if err != nil {
			log.Debug("unmarshal collection info failed", zap.Error(err))
			continue
		}
		if collMeta.Schema.Name == collectionName {
			return &collMeta, nil
		}
	}
	return nil, fmt.Errorf("can't find collection: %s, at timestamp = %d", collectionName, ts)
N
neza2017 已提交
433 434 435 436 437 438 439 440
}

func (mt *metaTable) GetCollectionBySegmentID(segID typeutil.UniqueID) (*pb.CollectionInfo, error) {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

	vid, ok := mt.segID2CollID[segID]
	if !ok {
S
sunby 已提交
441
		return nil, fmt.Errorf("segment id %d not belong to any collection", segID)
442 443 444
	}
	col, ok := mt.collID2Meta[vid]
	if !ok {
S
sunby 已提交
445
		return nil, fmt.Errorf("can't find collection id: %d", vid)
446
	}
N
neza2017 已提交
447 448
	colCopy := proto.Clone(&col)
	return colCopy.(*pb.CollectionInfo), nil
449 450
}

451
func (mt *metaTable) ListCollections(ts typeutil.Timestamp) (map[string]typeutil.UniqueID, error) {
452 453 454
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

455
	if ts == 0 {
456
		return mt.collName2ID, nil
457 458 459
	}
	_, vals, err := mt.client.LoadWithPrefix(CollectionMetaPrefix, ts)
	if err != nil {
N
neza2017 已提交
460
		log.Debug("load with prefix error", zap.Uint64("timestamp", ts), zap.Error(err))
461
		return nil, nil
462
	}
463
	colls := make(map[string]typeutil.UniqueID)
464 465 466 467 468 469
	for _, val := range vals {
		collMeta := pb.CollectionInfo{}
		err := proto.UnmarshalText(val, &collMeta)
		if err != nil {
			log.Debug("unmarshal collection info failed", zap.Error(err))
		}
470
		colls[collMeta.Schema.Name] = collMeta.ID
471 472 473 474
	}
	return colls, nil
}

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
// ListCollectionVirtualChannels list virtual channel of all the collection
func (mt *metaTable) ListCollectionVirtualChannels() []string {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
	vlist := []string{}

	for _, c := range mt.collID2Meta {
		vlist = append(vlist, c.VirtualChannelNames...)
	}
	return vlist
}

// ListCollectionPhysicalChannels list physical channel of all the collection
func (mt *metaTable) ListCollectionPhysicalChannels() []string {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
	plist := []string{}

	for _, c := range mt.collID2Meta {
		plist = append(plist, c.PhysicalChannelNames...)
	}
	return plist
}

N
neza2017 已提交
499
func (mt *metaTable) AddPartition(collID typeutil.UniqueID, partitionName string, partitionID typeutil.UniqueID, ddOpStr func(ts typeutil.Timestamp) (string, error)) (typeutil.Timestamp, error) {
500 501 502 503
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
	coll, ok := mt.collID2Meta[collID]
	if !ok {
504
		return 0, fmt.Errorf("can't find collection. id = %d", collID)
505 506 507
	}

	// number of partition tags (except _default) should be limited to 4096 by default
N
neza2017 已提交
508
	if int64(len(coll.PartitionIDs)) >= Params.MaxPartitionNum {
509
		return 0, fmt.Errorf("maximum partition's number should be limit to %d", Params.MaxPartitionNum)
510
	}
Z
zhenshan.cao 已提交
511 512 513
	for _, t := range coll.PartitionIDs {
		part, ok := mt.partitionID2Meta[t]
		if !ok {
N
neza2017 已提交
514
			log.Warn("partition id not exist", zap.Int64("partition id", t))
Z
zhenshan.cao 已提交
515 516 517
			continue
		}
		if part.PartitionName == partitionName {
518
			return 0, fmt.Errorf("partition name = %s already exists", partitionName)
519
		}
Z
zhenshan.cao 已提交
520
		if part.PartitionID == partitionID {
521
			return 0, fmt.Errorf("partition id = %d already exists", partitionID)
Z
zhenshan.cao 已提交
522 523 524 525 526 527
		}
	}
	partMeta := pb.PartitionInfo{
		PartitionName: partitionName,
		PartitionID:   partitionID,
		SegmentIDs:    make([]typeutil.UniqueID, 0, 16),
528 529
	}
	coll.PartitionIDs = append(coll.PartitionIDs, partitionID)
Z
zhenshan.cao 已提交
530 531
	mt.partitionID2Meta[partitionID] = partMeta
	mt.collID2Meta[collID] = coll
N
neza2017 已提交
532
	mt.partitionID2CollID[partitionID] = collID
Z
zhenshan.cao 已提交
533

N
neza2017 已提交
534
	k1 := fmt.Sprintf("%s/%d", CollectionMetaPrefix, collID)
Z
zhenshan.cao 已提交
535
	v1 := proto.MarshalTextString(&coll)
N
neza2017 已提交
536
	k2 := fmt.Sprintf("%s/%d/%d", PartitionMetaPrefix, collID, partitionID)
Z
zhenshan.cao 已提交
537 538 539
	v2 := proto.MarshalTextString(&partMeta)
	meta := map[string]string{k1: v1, k2: v2}

540
	// save ddOpStr into etcd
N
neza2017 已提交
541
	addition := mt.getAdditionKV(ddOpStr, meta)
542

N
neza2017 已提交
543
	ts, err := mt.client.MultiSave(meta, addition)
544 545
	if err != nil {
		_ = mt.reloadFromKV()
546
		return 0, err
547
	}
548
	return ts, nil
549 550
}

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
func (mt *metaTable) getPartitionByName(collID typeutil.UniqueID, partitionName string, ts typeutil.Timestamp) (pb.PartitionInfo, error) {
	if ts == 0 {
		collMeta, ok := mt.collID2Meta[collID]
		if !ok {
			return pb.PartitionInfo{}, fmt.Errorf("can't find collection id = %d", collID)
		}
		for _, id := range collMeta.PartitionIDs {
			partMeta, ok := mt.partitionID2Meta[id]
			if ok && partMeta.PartitionName == partitionName {
				return partMeta, nil
			}
		}
		return pb.PartitionInfo{}, fmt.Errorf("partition %s does not exist", partitionName)
	}
	collKey := fmt.Sprintf("%s/%d", CollectionMetaPrefix, collID)
	collVal, err := mt.client.Load(collKey, ts)
	if err != nil {
		return pb.PartitionInfo{}, err
	}
	collMeta := pb.CollectionMeta{}
	err = proto.UnmarshalText(collVal, &collMeta)
	if err != nil {
		return pb.PartitionInfo{}, err
574
	}
575
	for _, id := range collMeta.PartitionIDs {
576 577 578 579 580 581 582 583 584 585 586 587 588
		partKey := fmt.Sprintf("%s/%d/%d", PartitionMetaPrefix, collID, id)
		partVal, err := mt.client.Load(partKey, ts)
		if err != nil {
			log.Debug("load partition meta failed", zap.String("collection name", collMeta.Schema.Name), zap.Int64("partition id", id))
			continue
		}
		partMeta := pb.PartitionInfo{}
		err = proto.UnmarshalText(partVal, &partMeta)
		if err != nil {
			log.Debug("unmarshal partition meta failed", zap.Error(err))
			continue
		}
		if partMeta.PartitionName == partitionName {
589
			return partMeta, nil
590 591
		}
	}
592 593 594
	return pb.PartitionInfo{}, fmt.Errorf("partition %s does not exist", partitionName)
}

595
func (mt *metaTable) GetPartitionByName(collID typeutil.UniqueID, partitionName string, ts typeutil.Timestamp) (pb.PartitionInfo, error) {
596 597
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
598
	return mt.getPartitionByName(collID, partitionName, ts)
599 600
}

601
func (mt *metaTable) HasPartition(collID typeutil.UniqueID, partitionName string, ts typeutil.Timestamp) bool {
602 603
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
604
	_, err := mt.getPartitionByName(collID, partitionName, ts)
605 606 607
	return err == nil
}

608
//return timestamp, partitionid, error
N
neza2017 已提交
609
func (mt *metaTable) DeletePartition(collID typeutil.UniqueID, partitionName string, ddOpStr func(ts typeutil.Timestamp) (string, error)) (typeutil.Timestamp, typeutil.UniqueID, error) {
610 611 612
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

Z
zhenshan.cao 已提交
613
	if partitionName == Params.DefaultPartitionName {
614
		return 0, 0, fmt.Errorf("default partition cannot be deleted")
615 616 617 618
	}

	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
619
		return 0, 0, fmt.Errorf("can't find collection id = %d", collID)
620 621 622 623 624 625
	}

	// check tag exists
	exist := false

	pd := make([]typeutil.UniqueID, 0, len(collMeta.PartitionIDs))
Z
zhenshan.cao 已提交
626 627 628 629 630 631 632 633 634 635
	var partMeta pb.PartitionInfo
	for _, t := range collMeta.PartitionIDs {
		pm, ok := mt.partitionID2Meta[t]
		if ok {
			if pm.PartitionName != partitionName {
				pd = append(pd, pm.PartitionID)
			} else {
				partMeta = pm
				exist = true
			}
636 637 638
		}
	}
	if !exist {
639
		return 0, 0, fmt.Errorf("partition %s does not exist", partitionName)
640
	}
Z
zhenshan.cao 已提交
641 642 643
	delete(mt.partitionID2Meta, partMeta.PartitionID)
	collMeta.PartitionIDs = pd
	mt.collID2Meta[collID] = collMeta
644

Z
zhenshan.cao 已提交
645
	for _, segID := range partMeta.SegmentIDs {
646 647 648 649
		delete(mt.segID2CollID, segID)
		delete(mt.segID2PartitionID, segID)
		delete(mt.flushedSegID, segID)

N
neza2017 已提交
650
		_, ok := mt.segID2IndexMeta[segID]
651
		if !ok {
N
neza2017 已提交
652
			log.Warn("segment has no index meta", zap.Int64("segment id", segID))
Z
zhenshan.cao 已提交
653
			continue
654
		}
Z
zhenshan.cao 已提交
655
		delete(mt.segID2IndexMeta, segID)
656
	}
657
	meta := map[string]string{path.Join(CollectionMetaPrefix, strconv.FormatInt(collID, 10)): proto.MarshalTextString(&collMeta)}
N
neza2017 已提交
658 659 660 661 662 663 664 665
	delMetaKeys := []string{
		fmt.Sprintf("%s/%d/%d", PartitionMetaPrefix, collMeta.ID, partMeta.PartitionID),
	}
	for _, idxInfo := range collMeta.FieldIndexes {
		k := fmt.Sprintf("%s/%d/%d/%d", SegmentIndexMetaPrefix, collMeta.ID, idxInfo.IndexID, partMeta.PartitionID)
		delMetaKeys = append(delMetaKeys, k)
	}

666
	// save ddOpStr into etcd
N
neza2017 已提交
667
	addition := mt.getAdditionKV(ddOpStr, meta)
668

N
neza2017 已提交
669
	ts, err := mt.client.MultiSaveAndRemoveWithPrefix(meta, delMetaKeys, addition)
670 671
	if err != nil {
		_ = mt.reloadFromKV()
672
		return 0, 0, err
673
	}
674
	return ts, partMeta.PartitionID, nil
675 676
}

677
func (mt *metaTable) GetPartitionByID(collID typeutil.UniqueID, partitionID typeutil.UniqueID, ts typeutil.Timestamp) (pb.PartitionInfo, error) {
678 679
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
680 681 682 683 684 685
	if ts == 0 {
		partMeta, ok := mt.partitionID2Meta[partitionID]
		if !ok {
			return pb.PartitionInfo{}, fmt.Errorf("partition id = %d not exist", partitionID)
		}
		return partMeta, nil
686
	}
687 688 689 690 691 692 693 694 695 696 697 698
	partKey := fmt.Sprintf("%s/%d/%d", PartitionMetaPrefix, collID, partitionID)
	partVal, err := mt.client.Load(partKey, ts)
	if err != nil {
		return pb.PartitionInfo{}, err
	}
	partInfo := pb.PartitionInfo{}
	err = proto.UnmarshalText(partVal, &partInfo)
	if err != nil {
		return pb.PartitionInfo{}, err
	}
	return partInfo, nil

699 700
}

701
func (mt *metaTable) AddSegment(segInfos []*datapb.SegmentInfo, msgStartPos string, msgEndPos string) (typeutil.Timestamp, error) {
702 703
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
704 705 706 707 708 709

	meta := make(map[string]string)
	for _, segInfo := range segInfos {
		collMeta, ok := mt.collID2Meta[segInfo.CollectionID]
		if !ok {
			return 0, fmt.Errorf("can't find collection id = %d", segInfo.CollectionID)
S
sunby 已提交
710
		}
711 712 713
		partMeta, ok := mt.partitionID2Meta[segInfo.PartitionID]
		if !ok {
			return 0, fmt.Errorf("can't find partition id = %d", segInfo.PartitionID)
714
		}
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
		exist := false
		for _, partID := range collMeta.PartitionIDs {
			if partID == segInfo.PartitionID {
				exist = true
				break
			}
		}
		if !exist {
			return 0, fmt.Errorf("partition id = %d, not belong to collection id = %d", segInfo.PartitionID, segInfo.CollectionID)
		}
		exist = false
		for _, segID := range partMeta.SegmentIDs {
			if segID == segInfo.ID {
				exist = true
			}
		}
		if exist {
			return 0, fmt.Errorf("segment id = %d exist", segInfo.ID)
		}
		partMeta.SegmentIDs = append(partMeta.SegmentIDs, segInfo.ID)
		mt.partitionID2Meta[segInfo.PartitionID] = partMeta
		mt.segID2CollID[segInfo.ID] = segInfo.CollectionID
		mt.segID2PartitionID[segInfo.ID] = segInfo.PartitionID

		k := fmt.Sprintf("%s/%d/%d", PartitionMetaPrefix, segInfo.CollectionID, segInfo.PartitionID)
		v := proto.MarshalTextString(&partMeta)
		meta[k] = v
742
	}
N
neza2017 已提交
743

744
	// AddSegment is invoked from DataCoord
745
	if msgStartPos != "" && msgEndPos != "" {
746 747
		meta[SegInfoMsgStartPosPrefix] = msgStartPos
		meta[SegInfoMsgEndPosPrefix] = msgEndPos
748
	}
749

750
	ts, err := mt.client.MultiSave(meta, nil)
751 752
	if err != nil {
		_ = mt.reloadFromKV()
753
		return 0, err
754
	}
755
	return ts, nil
756
}
N
neza2017 已提交
757

758
func (mt *metaTable) AddIndex(segIdxInfos []*pb.SegmentIndexInfo, msgStartPos string, msgEndPos string) (typeutil.Timestamp, error) {
N
neza2017 已提交
759 760 761
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
	meta := make(map[string]string)

	for _, segIdxInfo := range segIdxInfos {
		collID, ok := mt.segID2CollID[segIdxInfo.SegmentID]
		if !ok {
			return 0, fmt.Errorf("segment id = %d not belong to any collection", segIdxInfo.SegmentID)
		}
		collMeta, ok := mt.collID2Meta[collID]
		if !ok {
			return 0, fmt.Errorf("collection id = %d not found", collID)
		}
		partID, ok := mt.segID2PartitionID[segIdxInfo.SegmentID]
		if !ok {
			return 0, fmt.Errorf("segment id = %d not belong to any partition", segIdxInfo.SegmentID)
		}
		exist := false
		for _, fidx := range collMeta.FieldIndexes {
			if fidx.IndexID == segIdxInfo.IndexID {
				exist = true
				break
			}
		}
		if !exist {
			return 0, fmt.Errorf("index id = %d not found", segIdxInfo.IndexID)
N
neza2017 已提交
786
		}
N
neza2017 已提交
787

788 789 790 791 792 793 794 795 796
		segIdxMap, ok := mt.segID2IndexMeta[segIdxInfo.SegmentID]
		if !ok {
			idxMap := map[typeutil.UniqueID]pb.SegmentIndexInfo{segIdxInfo.IndexID: *segIdxInfo}
			mt.segID2IndexMeta[segIdxInfo.SegmentID] = &idxMap
		} else {
			tmpInfo, ok := (*segIdxMap)[segIdxInfo.IndexID]
			if ok {
				if SegmentIndexInfoEqual(segIdxInfo, &tmpInfo) {
					log.Debug("Identical SegmentIndexInfo already exist", zap.Int64("IndexID", segIdxInfo.IndexID))
797
					continue
798 799
				}
				return 0, fmt.Errorf("index id = %d exist", segIdxInfo.IndexID)
800
			}
801
		}
802 803 804 805 806 807 808 809 810

		if _, ok := mt.flushedSegID[segIdxInfo.SegmentID]; !ok {
			mt.flushedSegID[segIdxInfo.SegmentID] = true
		}

		(*(mt.segID2IndexMeta[segIdxInfo.SegmentID]))[segIdxInfo.IndexID] = *segIdxInfo
		k := fmt.Sprintf("%s/%d/%d/%d/%d", SegmentIndexMetaPrefix, collID, segIdxInfo.IndexID, partID, segIdxInfo.SegmentID)
		v := proto.MarshalTextString(segIdxInfo)
		meta[k] = v
811 812
	}

813
	// AddIndex is invoked from DataNode flush operation
814
	if msgStartPos != "" && msgEndPos != "" {
815 816
		meta[FlushedSegMsgStartPosPrefix] = msgStartPos
		meta[FlushedSegMsgEndPosPrefix] = msgEndPos
817
	}
N
neza2017 已提交
818

819
	ts, err := mt.client.MultiSave(meta, nil)
N
neza2017 已提交
820 821
	if err != nil {
		_ = mt.reloadFromKV()
822
		return 0, err
N
neza2017 已提交
823
	}
824

825
	return ts, nil
N
neza2017 已提交
826 827
}

828 829
//return timestamp, index id, is dropped, error
func (mt *metaTable) DropIndex(collName, fieldName, indexName string) (typeutil.Timestamp, typeutil.UniqueID, bool, error) {
N
neza2017 已提交
830 831 832 833 834
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

	collID, ok := mt.collName2ID[collName]
	if !ok {
835
		return 0, 0, false, fmt.Errorf("collection name = %s not exist", collName)
N
neza2017 已提交
836 837 838
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
839
		return 0, 0, false, fmt.Errorf("collection name  = %s not has meta", collName)
N
neza2017 已提交
840 841 842
	}
	fieldSch, err := mt.unlockGetFieldSchema(collName, fieldName)
	if err != nil {
843
		return 0, 0, false, err
N
neza2017 已提交
844 845 846 847 848 849 850 851 852 853 854
	}
	fieldIdxInfo := make([]*pb.FieldIndexInfo, 0, len(collMeta.FieldIndexes))
	var dropIdxID typeutil.UniqueID
	for i, info := range collMeta.FieldIndexes {
		if info.FiledID != fieldSch.FieldID {
			fieldIdxInfo = append(fieldIdxInfo, info)
			continue
		}
		idxMeta, ok := mt.indexID2Meta[info.IndexID]
		if !ok {
			fieldIdxInfo = append(fieldIdxInfo, info)
N
neza2017 已提交
855
			log.Warn("index id not has meta", zap.Int64("index id", info.IndexID))
N
neza2017 已提交
856 857 858 859 860 861 862 863 864 865 866
			continue
		}
		if idxMeta.IndexName != indexName {
			fieldIdxInfo = append(fieldIdxInfo, info)
			continue
		}
		dropIdxID = info.IndexID
		fieldIdxInfo = append(fieldIdxInfo, collMeta.FieldIndexes[i+1:]...)
		break
	}
	if len(fieldIdxInfo) == len(collMeta.FieldIndexes) {
N
neza2017 已提交
867
		log.Warn("drop index,index not found", zap.String("collection name", collName), zap.String("filed name", fieldName), zap.String("index name", indexName))
868
		return 0, 0, false, nil
N
neza2017 已提交
869 870 871 872 873 874 875 876 877 878
	}
	collMeta.FieldIndexes = fieldIdxInfo
	mt.collID2Meta[collID] = collMeta
	saveMeta := map[string]string{path.Join(CollectionMetaPrefix, strconv.FormatInt(collID, 10)): proto.MarshalTextString(&collMeta)}

	delete(mt.indexID2Meta, dropIdxID)

	for _, partID := range collMeta.PartitionIDs {
		partMeta, ok := mt.partitionID2Meta[partID]
		if !ok {
N
neza2017 已提交
879
			log.Warn("partition not exist", zap.Int64("partition id", partID))
N
neza2017 已提交
880 881 882 883 884 885 886 887 888 889 890 891
			continue
		}
		for _, segID := range partMeta.SegmentIDs {
			segInfo, ok := mt.segID2IndexMeta[segID]
			if ok {
				_, ok := (*segInfo)[dropIdxID]
				if ok {
					delete(*segInfo, dropIdxID)
				}
			}
		}
	}
N
neza2017 已提交
892 893 894 895
	delMeta := []string{
		fmt.Sprintf("%s/%d/%d", SegmentIndexMetaPrefix, collMeta.ID, dropIdxID),
		fmt.Sprintf("%s/%d/%d", IndexMetaPrefix, collMeta.ID, dropIdxID),
	}
N
neza2017 已提交
896

N
neza2017 已提交
897
	ts, err := mt.client.MultiSaveAndRemoveWithPrefix(saveMeta, delMeta, nil)
N
neza2017 已提交
898 899
	if err != nil {
		_ = mt.reloadFromKV()
900
		return 0, 0, false, err
N
neza2017 已提交
901 902
	}

903
	return ts, dropIdxID, true, nil
N
neza2017 已提交
904 905
}

N
neza2017 已提交
906 907 908 909
func (mt *metaTable) GetSegmentIndexInfoByID(segID typeutil.UniqueID, filedID int64, idxName string) (pb.SegmentIndexInfo, error) {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

910 911
	_, ok := mt.flushedSegID[segID]
	if !ok {
912
		return pb.SegmentIndexInfo{}, fmt.Errorf("segment id %d hasn't flushed, there is no index meta", segID)
913 914
	}

N
neza2017 已提交
915 916
	segIdxMap, ok := mt.segID2IndexMeta[segID]
	if !ok {
917 918 919 920 921 922 923
		return pb.SegmentIndexInfo{
			SegmentID:   segID,
			FieldID:     filedID,
			IndexID:     0,
			BuildID:     0,
			EnableIndex: false,
		}, nil
N
neza2017 已提交
924 925
	}
	if len(*segIdxMap) == 0 {
S
sunby 已提交
926
		return pb.SegmentIndexInfo{}, fmt.Errorf("segment id %d not has any index", segID)
N
neza2017 已提交
927 928
	}

B
bigsheeper 已提交
929
	if filedID == -1 && idxName == "" { // return default index
N
neza2017 已提交
930
		for _, seg := range *segIdxMap {
B
bigsheeper 已提交
931 932 933 934
			info, ok := mt.indexID2Meta[seg.IndexID]
			if ok && info.IndexName == Params.DefaultIndexName {
				return seg, nil
			}
N
neza2017 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
		}
	} else {
		for idxID, seg := range *segIdxMap {
			idxMeta, ok := mt.indexID2Meta[idxID]
			if ok {
				if idxMeta.IndexName != idxName {
					continue
				}
				if seg.FieldID != filedID {
					continue
				}
				return seg, nil
			}
		}
	}
S
sunby 已提交
950
	return pb.SegmentIndexInfo{}, fmt.Errorf("can't find index name = %s on segment = %d, with filed id = %d", idxName, segID, filedID)
N
neza2017 已提交
951 952 953 954 955 956
}

func (mt *metaTable) GetFieldSchema(collName string, fieldName string) (schemapb.FieldSchema, error) {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

N
neza2017 已提交
957 958 959 960
	return mt.unlockGetFieldSchema(collName, fieldName)
}

func (mt *metaTable) unlockGetFieldSchema(collName string, fieldName string) (schemapb.FieldSchema, error) {
N
neza2017 已提交
961 962
	collID, ok := mt.collName2ID[collName]
	if !ok {
S
sunby 已提交
963
		return schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
964 965 966
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
S
sunby 已提交
967
		return schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
968 969 970 971 972 973 974
	}

	for _, field := range collMeta.Schema.Fields {
		if field.Name == fieldName {
			return *field, nil
		}
	}
S
sunby 已提交
975
	return schemapb.FieldSchema{}, fmt.Errorf("collection %s doesn't have filed %s", collName, fieldName)
N
neza2017 已提交
976 977 978 979 980 981
}

//return true/false
func (mt *metaTable) IsSegmentIndexed(segID typeutil.UniqueID, fieldSchema *schemapb.FieldSchema, indexParams []*commonpb.KeyValuePair) bool {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
N
neza2017 已提交
982 983 984 985
	return mt.unlockIsSegmentIndexed(segID, fieldSchema, indexParams)
}

func (mt *metaTable) unlockIsSegmentIndexed(segID typeutil.UniqueID, fieldSchema *schemapb.FieldSchema, indexParams []*commonpb.KeyValuePair) bool {
N
neza2017 已提交
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	segIdx, ok := mt.segID2IndexMeta[segID]
	if !ok {
		return false
	}
	exist := false
	for idxID, meta := range *segIdx {
		if meta.FieldID != fieldSchema.FieldID {
			continue
		}
		idxMeta, ok := mt.indexID2Meta[idxID]
		if !ok {
			continue
		}
		if EqualKeyPairArray(indexParams, idxMeta.IndexParams) {
			exist = true
			break
		}
	}
	return exist
}

// return segment ids, type params, error
N
neza2017 已提交
1008
func (mt *metaTable) GetNotIndexedSegments(collName string, fieldName string, idxInfo *pb.IndexInfo) ([]typeutil.UniqueID, schemapb.FieldSchema, error) {
N
neza2017 已提交
1009 1010 1011
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

N
neza2017 已提交
1012 1013 1014
	if idxInfo.IndexParams == nil {
		return nil, schemapb.FieldSchema{}, fmt.Errorf("index param is nil")
	}
N
neza2017 已提交
1015 1016
	collID, ok := mt.collName2ID[collName]
	if !ok {
S
sunby 已提交
1017
		return nil, schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
1018 1019 1020
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
S
sunby 已提交
1021
		return nil, schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
1022
	}
N
neza2017 已提交
1023
	fieldSchema, err := mt.unlockGetFieldSchema(collName, fieldName)
N
neza2017 已提交
1024 1025 1026 1027
	if err != nil {
		return nil, fieldSchema, err
	}

N
neza2017 已提交
1028 1029
	var dupIdx typeutil.UniqueID = 0
	for _, f := range collMeta.FieldIndexes {
1030 1031 1032 1033
		if info, ok := mt.indexID2Meta[f.IndexID]; ok {
			if info.IndexName == idxInfo.IndexName {
				dupIdx = info.IndexID
				break
N
neza2017 已提交
1034 1035 1036
			}
		}
	}
N
neza2017 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

	exist := false
	var existInfo pb.IndexInfo
	for _, f := range collMeta.FieldIndexes {
		if f.FiledID == fieldSchema.FieldID {
			existInfo, ok = mt.indexID2Meta[f.IndexID]
			if !ok {
				return nil, schemapb.FieldSchema{}, fmt.Errorf("index id = %d not found", f.IndexID)
			}
			if EqualKeyPairArray(existInfo.IndexParams, idxInfo.IndexParams) {
				exist = true
				break
			}
		}
	}
	if !exist {
N
neza2017 已提交
1053
		idx := &pb.FieldIndexInfo{
N
neza2017 已提交
1054 1055
			FiledID: fieldSchema.FieldID,
			IndexID: idxInfo.IndexID,
N
neza2017 已提交
1056 1057
		}
		collMeta.FieldIndexes = append(collMeta.FieldIndexes, idx)
N
neza2017 已提交
1058 1059 1060 1061
		mt.collID2Meta[collMeta.ID] = collMeta
		k1 := path.Join(CollectionMetaPrefix, strconv.FormatInt(collMeta.ID, 10))
		v1 := proto.MarshalTextString(&collMeta)

N
neza2017 已提交
1062 1063
		mt.indexID2Meta[idx.IndexID] = *idxInfo
		k2 := path.Join(IndexMetaPrefix, strconv.FormatInt(idx.IndexID, 10))
Z
zhenshan.cao 已提交
1064
		v2 := proto.MarshalTextString(idxInfo)
N
neza2017 已提交
1065 1066
		meta := map[string]string{k1: v1, k2: v2}

N
neza2017 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075
		if dupIdx != 0 {
			dupInfo := mt.indexID2Meta[dupIdx]
			dupInfo.IndexName = dupInfo.IndexName + "_bak"
			mt.indexID2Meta[dupIdx] = dupInfo
			k := path.Join(IndexMetaPrefix, strconv.FormatInt(dupInfo.IndexID, 10))
			v := proto.MarshalTextString(&dupInfo)
			meta[k] = v
		}

N
neza2017 已提交
1076
		_, err = mt.client.MultiSave(meta, nil)
N
neza2017 已提交
1077 1078 1079 1080 1081
		if err != nil {
			_ = mt.reloadFromKV()
			return nil, schemapb.FieldSchema{}, err
		}

N
neza2017 已提交
1082 1083 1084 1085 1086 1087 1088
	} else {
		idxInfo.IndexID = existInfo.IndexID
		if existInfo.IndexName != idxInfo.IndexName { //replace index name
			existInfo.IndexName = idxInfo.IndexName
			mt.indexID2Meta[existInfo.IndexID] = existInfo
			k := path.Join(IndexMetaPrefix, strconv.FormatInt(existInfo.IndexID, 10))
			v := proto.MarshalTextString(&existInfo)
N
neza2017 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
			meta := map[string]string{k: v}
			if dupIdx != 0 {
				dupInfo := mt.indexID2Meta[dupIdx]
				dupInfo.IndexName = dupInfo.IndexName + "_bak"
				mt.indexID2Meta[dupIdx] = dupInfo
				k := path.Join(IndexMetaPrefix, strconv.FormatInt(dupInfo.IndexID, 10))
				v := proto.MarshalTextString(&dupInfo)
				meta[k] = v
			}

N
neza2017 已提交
1099
			_, err = mt.client.MultiSave(meta, nil)
N
neza2017 已提交
1100 1101 1102 1103 1104
			if err != nil {
				_ = mt.reloadFromKV()
				return nil, schemapb.FieldSchema{}, err
			}
		}
N
neza2017 已提交
1105 1106
	}

N
neza2017 已提交
1107 1108 1109 1110 1111
	rstID := make([]typeutil.UniqueID, 0, 16)
	for _, partID := range collMeta.PartitionIDs {
		partMeta, ok := mt.partitionID2Meta[partID]
		if ok {
			for _, segID := range partMeta.SegmentIDs {
N
neza2017 已提交
1112
				if exist := mt.unlockIsSegmentIndexed(segID, &fieldSchema, idxInfo.IndexParams); !exist {
N
neza2017 已提交
1113 1114 1115 1116 1117 1118 1119 1120
					rstID = append(rstID, segID)
				}
			}
		}
	}
	return rstID, fieldSchema, nil
}

1121
func (mt *metaTable) GetIndexByName(collName, indexName string) (pb.CollectionInfo, []pb.IndexInfo, error) {
N
neza2017 已提交
1122
	mt.ddLock.RLock()
S
sunby 已提交
1123
	defer mt.ddLock.RUnlock()
N
neza2017 已提交
1124 1125 1126

	collID, ok := mt.collName2ID[collName]
	if !ok {
1127
		return pb.CollectionInfo{}, nil, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
1128 1129 1130
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
1131
		return pb.CollectionInfo{}, nil, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
1132 1133
	}

N
neza2017 已提交
1134
	rstIndex := make([]pb.IndexInfo, 0, len(collMeta.FieldIndexes))
Z
zhenshan.cao 已提交
1135
	for _, idx := range collMeta.FieldIndexes {
1136 1137
		idxInfo, ok := mt.indexID2Meta[idx.IndexID]
		if !ok {
1138
			return pb.CollectionInfo{}, nil, fmt.Errorf("index id = %d not found", idx.IndexID)
1139 1140 1141
		}
		if indexName == "" || idxInfo.IndexName == indexName {
			rstIndex = append(rstIndex, idxInfo)
N
neza2017 已提交
1142 1143
		}
	}
1144
	return collMeta, rstIndex, nil
N
neza2017 已提交
1145
}
B
bigsheeper 已提交
1146 1147 1148

func (mt *metaTable) GetIndexByID(indexID typeutil.UniqueID) (*pb.IndexInfo, error) {
	mt.ddLock.RLock()
S
sunby 已提交
1149
	defer mt.ddLock.RUnlock()
B
bigsheeper 已提交
1150 1151 1152

	indexInfo, ok := mt.indexID2Meta[indexID]
	if !ok {
S
sunby 已提交
1153
		return nil, fmt.Errorf("cannot find index, id = %d", indexID)
B
bigsheeper 已提交
1154 1155 1156
	}
	return &indexInfo, nil
}
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

func (mt *metaTable) AddFlushedSegment(segID typeutil.UniqueID) error {
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

	_, ok := mt.flushedSegID[segID]
	if ok {
		return fmt.Errorf("segment id = %d exist", segID)
	}
	mt.flushedSegID[segID] = true
	return nil
}