meta_table.go 36.6 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 (
S
sunby 已提交
15
	"fmt"
Z
zhenshan.cao 已提交
16
	"path"
17 18 19 20
	"strconv"
	"sync"

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

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

Z
zhenshan.cao 已提交
31
const (
Y
Yusup 已提交
32 33 34 35 36 37 38
	ComponentPrefix           = "root-coord"
	TenantMetaPrefix          = ComponentPrefix + "/tenant"
	ProxyMetaPrefix           = ComponentPrefix + "/proxy"
	CollectionMetaPrefix      = ComponentPrefix + "/collection"
	SegmentIndexMetaPrefix    = ComponentPrefix + "/segment-index"
	IndexMetaPrefix           = ComponentPrefix + "/index"
	CollectionAliasMetaPrefix = ComponentPrefix + "/collection-alias"
39

40 41
	TimestampPrefix = ComponentPrefix + "/timestamp"

42 43
	DDOperationPrefix = ComponentPrefix + "/dd-operation"
	DDMsgSendPrefix   = ComponentPrefix + "/dd-msg-send"
44

45 46 47 48
	CreateCollectionDDType = "CreateCollection"
	DropCollectionDDType   = "DropCollection"
	CreatePartitionDDType  = "CreatePartition"
	DropPartitionDDType    = "DropPartition"
Y
Yusup 已提交
49 50 51
	CreateAliasDDType      = "CreateAlias"
	DropAliasDDType        = "DropAlias"
	AlterAliasDDType       = "AlterAlias"
Z
zhenshan.cao 已提交
52 53
)

54
type metaTable struct {
55 56 57 58 59
	client          kv.SnapShotKV                                                   // client of a reliable kv service, i.e. etcd client
	tenantID2Meta   map[typeutil.UniqueID]pb.TenantMeta                             // tenant id to tenant meta
	proxyID2Meta    map[typeutil.UniqueID]pb.ProxyMeta                              // proxy id to proxy meta
	collID2Meta     map[typeutil.UniqueID]pb.CollectionInfo                         // collection_id -> meta
	collName2ID     map[string]typeutil.UniqueID                                    // collection name to collection id
Y
Yusup 已提交
60
	collAlias2ID    map[string]typeutil.UniqueID                                    // collection alias to collection id
61
	partID2SegID    map[typeutil.UniqueID]map[typeutil.UniqueID]bool                // partition_id -> segment_id -> bool
62 63
	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
64 65 66 67 68 69

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

70
func NewMetaTable(kv kv.SnapShotKV) (*metaTable, error) {
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
	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 已提交
88
	mt.collID2Meta = make(map[typeutil.UniqueID]pb.CollectionInfo)
89
	mt.collName2ID = make(map[string]typeutil.UniqueID)
Y
Yusup 已提交
90
	mt.collAlias2ID = make(map[string]typeutil.UniqueID)
91
	mt.partID2SegID = make(map[typeutil.UniqueID]map[typeutil.UniqueID]bool)
92
	mt.segID2IndexMeta = make(map[typeutil.UniqueID]map[typeutil.UniqueID]pb.SegmentIndexInfo)
Z
zhenshan.cao 已提交
93
	mt.indexID2Meta = make(map[typeutil.UniqueID]pb.IndexInfo)
94

95
	_, values, err := mt.client.LoadWithPrefix(TenantMetaPrefix, 0)
96 97 98 99 100 101 102 103
	if err != nil {
		return err
	}

	for _, value := range values {
		tenantMeta := pb.TenantMeta{}
		err := proto.UnmarshalText(value, &tenantMeta)
		if err != nil {
C
Cai Yudong 已提交
104
			return fmt.Errorf("RootCoord UnmarshalText pb.TenantMeta err:%w", err)
105 106 107 108
		}
		mt.tenantID2Meta[tenantMeta.ID] = tenantMeta
	}

109
	_, values, err = mt.client.LoadWithPrefix(ProxyMetaPrefix, 0)
110 111 112 113 114 115 116 117
	if err != nil {
		return err
	}

	for _, value := range values {
		proxyMeta := pb.ProxyMeta{}
		err = proto.UnmarshalText(value, &proxyMeta)
		if err != nil {
C
Cai Yudong 已提交
118
			return fmt.Errorf("RootCoord UnmarshalText pb.ProxyMeta err:%w", err)
119 120 121 122
		}
		mt.proxyID2Meta[proxyMeta.ID] = proxyMeta
	}

123
	_, values, err = mt.client.LoadWithPrefix(CollectionMetaPrefix, 0)
124 125 126 127 128
	if err != nil {
		return err
	}

	for _, value := range values {
129 130
		collInfo := pb.CollectionInfo{}
		err = proto.UnmarshalText(value, &collInfo)
131
		if err != nil {
C
Cai Yudong 已提交
132
			return fmt.Errorf("RootCoord UnmarshalText pb.CollectionInfo err:%w", err)
133
		}
134 135
		mt.collID2Meta[collInfo.ID] = collInfo
		mt.collName2ID[collInfo.Schema.Name] = collInfo.ID
136 137
	}

138
	_, values, err = mt.client.LoadWithPrefix(SegmentIndexMetaPrefix, 0)
139 140 141
	if err != nil {
		return err
	}
Z
zhenshan.cao 已提交
142 143 144
	for _, value := range values {
		segmentIndexInfo := pb.SegmentIndexInfo{}
		err = proto.UnmarshalText(value, &segmentIndexInfo)
145
		if err != nil {
C
Cai Yudong 已提交
146
			return fmt.Errorf("RootCoord UnmarshalText pb.SegmentIndexInfo err:%w", err)
147
		}
148 149 150 151 152 153 154 155 156 157 158 159

		// update partID2SegID
		segIDMap, ok := mt.partID2SegID[segmentIndexInfo.PartitionID]
		if ok {
			segIDMap[segmentIndexInfo.SegmentID] = true
		} else {
			idMap := make(map[typeutil.UniqueID]bool)
			idMap[segmentIndexInfo.SegmentID] = true
			mt.partID2SegID[segmentIndexInfo.PartitionID] = idMap
		}

		// update segID2IndexMeta
Z
zhenshan.cao 已提交
160
		idx, ok := mt.segID2IndexMeta[segmentIndexInfo.SegmentID]
161
		if ok {
162
			idx[segmentIndexInfo.IndexID] = segmentIndexInfo
Z
zhenshan.cao 已提交
163 164 165
		} else {
			meta := make(map[typeutil.UniqueID]pb.SegmentIndexInfo)
			meta[segmentIndexInfo.IndexID] = segmentIndexInfo
166
			mt.segID2IndexMeta[segmentIndexInfo.SegmentID] = meta
167 168 169
		}
	}

170
	_, values, err = mt.client.LoadWithPrefix(IndexMetaPrefix, 0)
Z
zhenshan.cao 已提交
171 172
	if err != nil {
		return err
173
	}
Z
zhenshan.cao 已提交
174 175 176 177
	for _, value := range values {
		meta := pb.IndexInfo{}
		err = proto.UnmarshalText(value, &meta)
		if err != nil {
C
Cai Yudong 已提交
178
			return fmt.Errorf("RootCoord UnmarshalText pb.IndexInfo err:%w", err)
179
		}
Z
zhenshan.cao 已提交
180
		mt.indexID2Meta[meta.IndexID] = meta
181 182
	}

Y
Yusup 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195
	_, values, err = mt.client.LoadWithPrefix(CollectionAliasMetaPrefix, 0)
	if err != nil {
		return err
	}
	for _, value := range values {
		aliasInfo := pb.CollectionInfo{}
		err = proto.UnmarshalText(value, &aliasInfo)
		if err != nil {
			return fmt.Errorf("RootCoord UnmarshalText pb.AliasInfo err:%w", err)
		}
		mt.collAlias2ID[aliasInfo.Schema.Name] = aliasInfo.ID
	}

196
	log.Debug("reload meta table from KV successfully")
Z
zhenshan.cao 已提交
197
	return nil
198 199
}

N
neza2017 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213
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
	}
}

214
func (mt *metaTable) AddTenant(te *pb.TenantMeta, ts typeutil.Timestamp) error {
N
neza2017 已提交
215 216 217 218 219 220
	mt.tenantLock.Lock()
	defer mt.tenantLock.Unlock()

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

221
	err := mt.client.Save(k, v, ts)
222
	if err != nil {
223 224
		log.Error("SnapShotKV Save fail", zap.Error(err))
		panic("SnapShotKV Save fail")
N
neza2017 已提交
225 226
	}
	mt.tenantID2Meta[te.ID] = *te
227
	return nil
N
neza2017 已提交
228 229
}

230
func (mt *metaTable) AddProxy(po *pb.ProxyMeta, ts typeutil.Timestamp) error {
N
neza2017 已提交
231 232 233 234 235 236
	mt.proxyLock.Lock()
	defer mt.proxyLock.Unlock()

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

237
	err := mt.client.Save(k, v, ts)
238
	if err != nil {
239 240
		log.Error("SnapShotKV Save fail", zap.Error(err))
		panic("SnapShotKV Save fail")
N
neza2017 已提交
241 242
	}
	mt.proxyID2Meta[po.ID] = *po
243
	return nil
N
neza2017 已提交
244 245
}

246
func (mt *metaTable) AddCollection(coll *pb.CollectionInfo, ts typeutil.Timestamp, idx []*pb.IndexInfo, ddOpStr func(ts typeutil.Timestamp) (string, error)) error {
247 248
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
Z
zhenshan.cao 已提交
249

250 251
	if len(coll.PartitionIDs) != len(coll.PartitionNames) ||
		len(coll.PartitionIDs) != len(coll.PartitionCreatedTimestamps) ||
252
		(len(coll.PartitionIDs) != 1 && len(coll.PartitionIDs) != 0) {
253
		return fmt.Errorf("PartitionIDs, PartitionNames and PartitionCreatedTimestmaps' length mis-match when creating collection")
254
	}
255
	if _, ok := mt.collName2ID[coll.Schema.Name]; ok {
256
		return fmt.Errorf("collection %s exist", coll.Schema.Name)
257
	}
N
neza2017 已提交
258
	if len(coll.FieldIndexes) != len(idx) {
259
		return fmt.Errorf("incorrect index id when creating collection")
N
neza2017 已提交
260
	}
261

N
neza2017 已提交
262 263 264
	for _, i := range idx {
		mt.indexID2Meta[i.IndexID] = *i
	}
Z
zhenshan.cao 已提交
265

266
	meta := make(map[string]string)
Z
zhenshan.cao 已提交
267

N
neza2017 已提交
268
	for _, i := range idx {
N
neza2017 已提交
269
		k := fmt.Sprintf("%s/%d/%d", IndexMetaPrefix, coll.ID, i.IndexID)
N
neza2017 已提交
270 271 272 273
		v := proto.MarshalTextString(i)
		meta[k] = v
	}

274
	// save ddOpStr into etcd
N
neza2017 已提交
275
	addition := mt.getAdditionKV(ddOpStr, meta)
276 277 278 279 280 281 282 283 284 285 286 287 288
	saveColl := func(ts typeutil.Timestamp) (string, string, error) {
		coll.CreateTime = ts
		if len(coll.PartitionCreatedTimestamps) == 1 {
			coll.PartitionCreatedTimestamps[0] = ts
		}
		mt.collID2Meta[coll.ID] = *coll
		mt.collName2ID[coll.Schema.Name] = coll.ID
		k1 := fmt.Sprintf("%s/%d", CollectionMetaPrefix, coll.ID)
		v1 := proto.MarshalTextString(coll)
		meta[k1] = v1
		return k1, v1, nil
	}

289
	err := mt.client.MultiSave(meta, ts, addition, saveColl)
290
	if err != nil {
291 292
		log.Error("SnapShotKV MultiSave fail", zap.Error(err))
		panic("SnapShotKV MultiSave fail")
293
	}
294

295
	return nil
296 297
}

298
func (mt *metaTable) DeleteCollection(collID typeutil.UniqueID, ts typeutil.Timestamp, ddOpStr func(ts typeutil.Timestamp) (string, error)) error {
299 300 301 302 303
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

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

Z
zhenshan.cao 已提交
307 308
	delete(mt.collID2Meta, collID)
	delete(mt.collName2ID, collMeta.Schema.Name)
309 310 311 312 313 314 315

	// update segID2IndexMeta
	for partID := range collMeta.PartitionIDs {
		if segIDMap, ok := mt.partID2SegID[typeutil.UniqueID(partID)]; ok {
			for segID := range segIDMap {
				delete(mt.segID2IndexMeta, segID)
			}
Z
zhenshan.cao 已提交
316 317
		}
	}
318 319 320 321 322 323

	// update partID2SegID
	for partID := range collMeta.PartitionIDs {
		delete(mt.partID2SegID, typeutil.UniqueID(partID))
	}

N
neza2017 已提交
324 325 326 327 328 329 330 331
	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)
	}
Y
Yusup 已提交
332 333 334 335 336 337 338
	var aliases []string
	// delete collection aliases
	for alias, cid := range mt.collAlias2ID {
		if cid == collID {
			aliases = append(aliases, alias)
		}
	}
339

340
	delMetakeys := []string{
N
neza2017 已提交
341 342 343 344
		fmt.Sprintf("%s/%d", CollectionMetaPrefix, collID),
		fmt.Sprintf("%s/%d", SegmentIndexMetaPrefix, collID),
		fmt.Sprintf("%s/%d", IndexMetaPrefix, collID),
	}
345

Y
Yusup 已提交
346 347 348 349 350 351 352
	for _, alias := range aliases {
		delete(mt.collAlias2ID, alias)
		delMetakeys = append(delMetakeys,
			fmt.Sprintf("%s/%s", CollectionAliasMetaPrefix, alias),
		)
	}

353
	// save ddOpStr into etcd
N
neza2017 已提交
354 355
	var saveMeta = map[string]string{}
	addition := mt.getAdditionKV(ddOpStr, saveMeta)
356
	err := mt.client.MultiSaveAndRemoveWithPrefix(saveMeta, delMetakeys, ts, addition)
357
	if err != nil {
358 359
		log.Error("SnapShotKV MultiSaveAndRemoveWithPrefix fail", zap.Error(err))
		panic("SnapShotKV MultiSaveAndRemoveWithPrefix fail")
360 361
	}

362
	return nil
363 364
}

365
func (mt *metaTable) HasCollection(collID typeutil.UniqueID, ts typeutil.Timestamp) bool {
366 367
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
368 369 370 371 372 373 374
	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
375 376
}

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

381 382 383 384 385 386 387
	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 已提交
388
	}
389 390 391 392 393 394 395 396 397 398 399
	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 已提交
400 401
}

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

406 407 408
	if ts == 0 {
		vid, ok := mt.collName2ID[collectionName]
		if !ok {
Y
Yusup 已提交
409 410 411
			if vid, ok = mt.collAlias2ID[collectionName]; !ok {
				return nil, fmt.Errorf("can't find collection: " + collectionName)
			}
412 413 414
		}
		col, ok := mt.collID2Meta[vid]
		if !ok {
S
sunby 已提交
415
			return nil, fmt.Errorf("can't find collection %s with id %d", collectionName, vid)
416 417 418
		}
		colCopy := proto.Clone(&col)
		return colCopy.(*pb.CollectionInfo), nil
N
neza2017 已提交
419
	}
420 421 422
	_, vals, err := mt.client.LoadWithPrefix(CollectionMetaPrefix, ts)
	if err != nil {
		return nil, err
N
neza2017 已提交
423
	}
424 425 426 427 428 429 430 431 432 433 434 435
	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 已提交
436 437
}

438
func (mt *metaTable) ListCollections(ts typeutil.Timestamp) (map[string]*pb.CollectionInfo, error) {
439 440
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
441
	colls := make(map[string]*pb.CollectionInfo)
442

443
	if ts == 0 {
444 445 446 447
		for collName, collID := range mt.collName2ID {
			coll := mt.collID2Meta[collID]
			colCopy := proto.Clone(&coll)
			colls[collName] = colCopy.(*pb.CollectionInfo)
N
neza2017 已提交
448 449
		}
		return colls, nil
450 451 452
	}
	_, vals, err := mt.client.LoadWithPrefix(CollectionMetaPrefix, ts)
	if err != nil {
N
neza2017 已提交
453
		log.Debug("load with prefix error", zap.Uint64("timestamp", ts), zap.Error(err))
454
		return nil, nil
455 456 457 458 459 460 461
	}
	for _, val := range vals {
		collMeta := pb.CollectionInfo{}
		err := proto.UnmarshalText(val, &collMeta)
		if err != nil {
			log.Debug("unmarshal collection info failed", zap.Error(err))
		}
462
		colls[collMeta.Schema.Name] = &collMeta
463 464 465 466
	}
	return colls, nil
}

467 468 469 470 471 472 473 474 475 476 477 478
func (mt *metaTable) ListAliases(collID typeutil.UniqueID) []string {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
	var aliases []string
	for alias, cid := range mt.collAlias2ID {
		if cid == collID {
			aliases = append(aliases, alias)
		}
	}
	return aliases
}

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
// 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
}

503
func (mt *metaTable) AddPartition(collID typeutil.UniqueID, partitionName string, partitionID typeutil.UniqueID, ts typeutil.Timestamp, ddOpStr func(ts typeutil.Timestamp) (string, error)) error {
504 505 506 507
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
	coll, ok := mt.collID2Meta[collID]
	if !ok {
508
		return fmt.Errorf("can't find collection. id = %d", collID)
509 510 511
	}

	// number of partition tags (except _default) should be limited to 4096 by default
N
neza2017 已提交
512
	if int64(len(coll.PartitionIDs)) >= Params.MaxPartitionNum {
513
		return fmt.Errorf("maximum partition's number should be limit to %d", Params.MaxPartitionNum)
514
	}
515

516
	if len(coll.PartitionIDs) != len(coll.PartitionNames) {
517
		return fmt.Errorf("len(coll.PartitionIDs)=%d, len(coll.PartitionNames)=%d", len(coll.PartitionIDs), len(coll.PartitionNames))
518 519
	}

520
	if len(coll.PartitionIDs) != len(coll.PartitionCreatedTimestamps) {
521
		return fmt.Errorf("len(coll.PartitionIDs)=%d, len(coll.PartitionCreatedTimestamps)=%d", len(coll.PartitionIDs), len(coll.PartitionCreatedTimestamps))
522 523 524
	}

	if len(coll.PartitionNames) != len(coll.PartitionCreatedTimestamps) {
525
		return fmt.Errorf("len(coll.PartitionNames)=%d, len(coll.PartitionCreatedTimestamps)=%d", len(coll.PartitionNames), len(coll.PartitionCreatedTimestamps))
526 527
	}

528 529
	for idx := range coll.PartitionIDs {
		if coll.PartitionIDs[idx] == partitionID {
530
			return fmt.Errorf("partition id = %d already exists", partitionID)
Z
zhenshan.cao 已提交
531
		}
532
		if coll.PartitionNames[idx] == partitionName {
533
			return fmt.Errorf("partition name = %s already exists", partitionName)
534
		}
535
		// no necessary to check created timestamp
536
	}
537
	meta := make(map[string]string)
Z
zhenshan.cao 已提交
538

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

542 543 544 545 546 547 548 549 550 551 552 553 554
	saveColl := func(ts typeutil.Timestamp) (string, string, error) {
		coll.PartitionIDs = append(coll.PartitionIDs, partitionID)
		coll.PartitionNames = append(coll.PartitionNames, partitionName)
		coll.PartitionCreatedTimestamps = append(coll.PartitionCreatedTimestamps, ts)
		mt.collID2Meta[collID] = coll

		k1 := fmt.Sprintf("%s/%d", CollectionMetaPrefix, collID)
		v1 := proto.MarshalTextString(&coll)
		meta[k1] = v1

		return k1, v1, nil
	}

555
	err := mt.client.MultiSave(meta, ts, addition, saveColl)
556
	if err != nil {
557 558
		log.Error("SnapShotKV MultiSave fail", zap.Error(err))
		panic("SnapShotKV MultiSave fail")
559
	}
560
	return nil
561 562
}

563
func (mt *metaTable) GetPartitionNameByID(collID, partitionID typeutil.UniqueID, ts typeutil.Timestamp) (string, error) {
564
	if ts == 0 {
565 566
		mt.ddLock.RLock()
		defer mt.ddLock.RUnlock()
567 568
		collMeta, ok := mt.collID2Meta[collID]
		if !ok {
569
			return "", fmt.Errorf("can't find collection id = %d", collID)
570
		}
571 572
		for idx := range collMeta.PartitionIDs {
			if collMeta.PartitionIDs[idx] == partitionID {
573
				return collMeta.PartitionNames[idx], nil
574 575
			}
		}
576
		return "", fmt.Errorf("partition %d does not exist", partitionID)
577 578 579 580
	}
	collKey := fmt.Sprintf("%s/%d", CollectionMetaPrefix, collID)
	collVal, err := mt.client.Load(collKey, ts)
	if err != nil {
581
		return "", err
582
	}
583
	collMeta := pb.CollectionInfo{}
584 585
	err = proto.UnmarshalText(collVal, &collMeta)
	if err != nil {
586
		return "", err
587
	}
588 589
	for idx := range collMeta.PartitionIDs {
		if collMeta.PartitionIDs[idx] == partitionID {
590
			return collMeta.PartitionNames[idx], nil
591
		}
592 593 594 595 596 597 598 599 600
	}
	return "", fmt.Errorf("partition %d does not exist", partitionID)
}

func (mt *metaTable) getPartitionByName(collID typeutil.UniqueID, partitionName string, ts typeutil.Timestamp) (typeutil.UniqueID, error) {
	if ts == 0 {
		collMeta, ok := mt.collID2Meta[collID]
		if !ok {
			return 0, fmt.Errorf("can't find collection id = %d", collID)
601
		}
602
		for idx := range collMeta.PartitionIDs {
603
			if collMeta.PartitionNames[idx] == partitionName {
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
				return collMeta.PartitionIDs[idx], nil
			}
		}
		return 0, 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 0, err
	}
	collMeta := pb.CollectionInfo{}
	err = proto.UnmarshalText(collVal, &collMeta)
	if err != nil {
		return 0, err
	}
	for idx := range collMeta.PartitionIDs {
620
		if collMeta.PartitionNames[idx] == partitionName {
621
			return collMeta.PartitionIDs[idx], nil
622 623
		}
	}
624
	return 0, fmt.Errorf("partition %s does not exist", partitionName)
625 626
}

627
func (mt *metaTable) GetPartitionByName(collID typeutil.UniqueID, partitionName string, ts typeutil.Timestamp) (typeutil.UniqueID, error) {
628 629
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
630
	return mt.getPartitionByName(collID, partitionName, ts)
631 632
}

633
func (mt *metaTable) HasPartition(collID typeutil.UniqueID, partitionName string, ts typeutil.Timestamp) bool {
634 635
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()
636
	_, err := mt.getPartitionByName(collID, partitionName, ts)
637 638 639
	return err == nil
}

640
func (mt *metaTable) DeletePartition(collID typeutil.UniqueID, partitionName string, ts typeutil.Timestamp, ddOpStr func(ts typeutil.Timestamp) (string, error)) (typeutil.UniqueID, error) {
641 642 643
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

Z
zhenshan.cao 已提交
644
	if partitionName == Params.DefaultPartitionName {
645
		return 0, fmt.Errorf("default partition cannot be deleted")
646 647 648 649
	}

	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
650
		return 0, fmt.Errorf("can't find collection id = %d", collID)
651 652 653 654 655 656
	}

	// check tag exists
	exist := false

	pd := make([]typeutil.UniqueID, 0, len(collMeta.PartitionIDs))
657
	pn := make([]string, 0, len(collMeta.PartitionNames))
658
	pts := make([]uint64, 0, len(collMeta.PartitionCreatedTimestamps))
659 660
	var partID typeutil.UniqueID
	for idx := range collMeta.PartitionIDs {
661
		if collMeta.PartitionNames[idx] == partitionName {
662 663 664 665
			partID = collMeta.PartitionIDs[idx]
			exist = true
		} else {
			pd = append(pd, collMeta.PartitionIDs[idx])
666
			pn = append(pn, collMeta.PartitionNames[idx])
667
			pts = append(pts, collMeta.PartitionCreatedTimestamps[idx])
668 669 670
		}
	}
	if !exist {
671
		return 0, fmt.Errorf("partition %s does not exist", partitionName)
672
	}
Z
zhenshan.cao 已提交
673
	collMeta.PartitionIDs = pd
674
	collMeta.PartitionNames = pn
675
	collMeta.PartitionCreatedTimestamps = pts
Z
zhenshan.cao 已提交
676
	mt.collID2Meta[collID] = collMeta
677

678 679 680 681
	// update segID2IndexMeta and partID2SegID
	if segIDMap, ok := mt.partID2SegID[partID]; ok {
		for segID := range segIDMap {
			delete(mt.segID2IndexMeta, segID)
682 683
		}
	}
684 685
	delete(mt.partID2SegID, partID)

686
	meta := map[string]string{path.Join(CollectionMetaPrefix, strconv.FormatInt(collID, 10)): proto.MarshalTextString(&collMeta)}
687
	delMetaKeys := []string{}
N
neza2017 已提交
688
	for _, idxInfo := range collMeta.FieldIndexes {
689
		k := fmt.Sprintf("%s/%d/%d/%d", SegmentIndexMetaPrefix, collMeta.ID, idxInfo.IndexID, partID)
N
neza2017 已提交
690 691 692
		delMetaKeys = append(delMetaKeys, k)
	}

693
	// save ddOpStr into etcd
N
neza2017 已提交
694
	addition := mt.getAdditionKV(ddOpStr, meta)
695

696
	err := mt.client.MultiSaveAndRemoveWithPrefix(meta, delMetaKeys, ts, addition)
697
	if err != nil {
698 699
		log.Error("SnapShotKV MultiSaveAndRemoveWithPrefix fail", zap.Error(err))
		panic("SnapShotKV MultiSaveAndRemoveWithPrefix fail")
700
	}
701
	return partID, nil
702 703
}

704
func (mt *metaTable) AddIndex(segIdxInfo *pb.SegmentIndexInfo, ts typeutil.Timestamp) error {
705 706
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
707

708
	collMeta, ok := mt.collID2Meta[segIdxInfo.CollectionID]
709
	if !ok {
710
		return fmt.Errorf("collection id = %d not found", segIdxInfo.CollectionID)
711
	}
712 713 714 715 716 717
	exist := false
	for _, fidx := range collMeta.FieldIndexes {
		if fidx.IndexID == segIdxInfo.IndexID {
			exist = true
			break
		}
718
	}
719
	if !exist {
720
		return fmt.Errorf("index id = %d not found", segIdxInfo.IndexID)
721
	}
722

723 724 725 726
	segIdxMap, ok := mt.segID2IndexMeta[segIdxInfo.SegmentID]
	if !ok {
		idxMap := map[typeutil.UniqueID]pb.SegmentIndexInfo{segIdxInfo.IndexID: *segIdxInfo}
		mt.segID2IndexMeta[segIdxInfo.SegmentID] = idxMap
727 728 729

		segIDMap := map[typeutil.UniqueID]bool{segIdxInfo.SegmentID: true}
		mt.partID2SegID[segIdxInfo.PartitionID] = segIDMap
730 731 732 733 734
	} else {
		tmpInfo, ok := segIdxMap[segIdxInfo.IndexID]
		if ok {
			if SegmentIndexInfoEqual(segIdxInfo, &tmpInfo) {
				if segIdxInfo.BuildID == tmpInfo.BuildID {
735
					log.Debug("Identical SegmentIndexInfo already exist", zap.Int64("IndexID", segIdxInfo.IndexID))
736
					return nil
737
				}
738
				return fmt.Errorf("index id = %d exist", segIdxInfo.IndexID)
739
			}
740 741 742
		}
	}

743
	mt.segID2IndexMeta[segIdxInfo.SegmentID][segIdxInfo.IndexID] = *segIdxInfo
744 745
	mt.partID2SegID[segIdxInfo.PartitionID][segIdxInfo.SegmentID] = true

746
	k := fmt.Sprintf("%s/%d/%d/%d/%d", SegmentIndexMetaPrefix, segIdxInfo.CollectionID, segIdxInfo.IndexID, segIdxInfo.PartitionID, segIdxInfo.SegmentID)
747
	v := proto.MarshalTextString(segIdxInfo)
N
neza2017 已提交
748

749
	err := mt.client.Save(k, v, ts)
N
neza2017 已提交
750
	if err != nil {
751 752
		log.Error("SnapShotKV Save fail", zap.Error(err))
		panic("SnapShotKV Save fail")
N
neza2017 已提交
753
	}
754

755
	return nil
N
neza2017 已提交
756 757
}

758
//return timestamp, index id, is dropped, error
759
func (mt *metaTable) DropIndex(collName, fieldName, indexName string, ts typeutil.Timestamp) (typeutil.UniqueID, bool, error) {
N
neza2017 已提交
760 761 762 763 764
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

	collID, ok := mt.collName2ID[collName]
	if !ok {
765
		return 0, false, fmt.Errorf("collection name = %s not exist", collName)
N
neza2017 已提交
766 767 768
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
769
		return 0, false, fmt.Errorf("collection name  = %s not has meta", collName)
N
neza2017 已提交
770 771 772
	}
	fieldSch, err := mt.unlockGetFieldSchema(collName, fieldName)
	if err != nil {
773
		return 0, false, err
N
neza2017 已提交
774 775 776 777 778 779 780 781 782 783 784
	}
	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 已提交
785
			log.Warn("index id not has meta", zap.Int64("index id", info.IndexID))
N
neza2017 已提交
786 787 788 789 790 791 792 793 794 795 796
			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 已提交
797
		log.Warn("drop index,index not found", zap.String("collection name", collName), zap.String("filed name", fieldName), zap.String("index name", indexName))
798
		return 0, false, nil
N
neza2017 已提交
799 800 801 802 803 804 805
	}
	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)

806 807 808 809 810 811 812
	// update segID2IndexMeta
	for partID := range collMeta.PartitionIDs {
		if segIDMap, ok := mt.partID2SegID[typeutil.UniqueID(partID)]; ok {
			for segID := range segIDMap {
				if segIndexInfos, ok := mt.segID2IndexMeta[segID]; ok {
					delete(segIndexInfos, dropIdxID)
				}
N
neza2017 已提交
813 814 815
			}
		}
	}
816

N
neza2017 已提交
817 818 819 820
	delMeta := []string{
		fmt.Sprintf("%s/%d/%d", SegmentIndexMetaPrefix, collMeta.ID, dropIdxID),
		fmt.Sprintf("%s/%d/%d", IndexMetaPrefix, collMeta.ID, dropIdxID),
	}
N
neza2017 已提交
821

822
	err = mt.client.MultiSaveAndRemoveWithPrefix(saveMeta, delMeta, ts)
N
neza2017 已提交
823
	if err != nil {
824 825
		log.Error("SnapShotKV MultiSaveAndRemoveWithPrefix fail", zap.Error(err))
		panic("SnapShotKV MultiSaveAndRemoveWithPrefix fail")
N
neza2017 已提交
826 827
	}

828
	return dropIdxID, true, nil
N
neza2017 已提交
829 830
}

N
neza2017 已提交
831 832 833 834 835 836
func (mt *metaTable) GetSegmentIndexInfoByID(segID typeutil.UniqueID, filedID int64, idxName string) (pb.SegmentIndexInfo, error) {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

	segIdxMap, ok := mt.segID2IndexMeta[segID]
	if !ok {
837 838 839 840 841 842 843
		return pb.SegmentIndexInfo{
			SegmentID:   segID,
			FieldID:     filedID,
			IndexID:     0,
			BuildID:     0,
			EnableIndex: false,
		}, nil
N
neza2017 已提交
844
	}
845
	if len(segIdxMap) == 0 {
S
sunby 已提交
846
		return pb.SegmentIndexInfo{}, fmt.Errorf("segment id %d not has any index", segID)
N
neza2017 已提交
847 848
	}

B
bigsheeper 已提交
849
	if filedID == -1 && idxName == "" { // return default index
850
		for _, seg := range segIdxMap {
B
bigsheeper 已提交
851 852 853 854
			info, ok := mt.indexID2Meta[seg.IndexID]
			if ok && info.IndexName == Params.DefaultIndexName {
				return seg, nil
			}
N
neza2017 已提交
855 856
		}
	} else {
857
		for idxID, seg := range segIdxMap {
N
neza2017 已提交
858 859 860 861 862 863 864 865 866 867 868 869
			idxMeta, ok := mt.indexID2Meta[idxID]
			if ok {
				if idxMeta.IndexName != idxName {
					continue
				}
				if seg.FieldID != filedID {
					continue
				}
				return seg, nil
			}
		}
	}
S
sunby 已提交
870
	return pb.SegmentIndexInfo{}, fmt.Errorf("can't find index name = %s on segment = %d, with filed id = %d", idxName, segID, filedID)
N
neza2017 已提交
871 872 873 874 875 876
}

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

N
neza2017 已提交
877 878 879 880
	return mt.unlockGetFieldSchema(collName, fieldName)
}

func (mt *metaTable) unlockGetFieldSchema(collName string, fieldName string) (schemapb.FieldSchema, error) {
N
neza2017 已提交
881 882
	collID, ok := mt.collName2ID[collName]
	if !ok {
S
sunby 已提交
883
		return schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
884 885 886
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
S
sunby 已提交
887
		return schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
888 889 890 891 892 893 894
	}

	for _, field := range collMeta.Schema.Fields {
		if field.Name == fieldName {
			return *field, nil
		}
	}
S
sunby 已提交
895
	return schemapb.FieldSchema{}, fmt.Errorf("collection %s doesn't have filed %s", collName, fieldName)
N
neza2017 已提交
896 897 898 899 900 901
}

//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 已提交
902 903 904 905
	return mt.unlockIsSegmentIndexed(segID, fieldSchema, indexParams)
}

func (mt *metaTable) unlockIsSegmentIndexed(segID typeutil.UniqueID, fieldSchema *schemapb.FieldSchema, indexParams []*commonpb.KeyValuePair) bool {
N
neza2017 已提交
906 907 908 909 910
	segIdx, ok := mt.segID2IndexMeta[segID]
	if !ok {
		return false
	}
	exist := false
911
	for idxID, meta := range segIdx {
N
neza2017 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
		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
C
congqixia 已提交
928
func (mt *metaTable) GetNotIndexedSegments(collName string, fieldName string, idxInfo *pb.IndexInfo, segIDs []typeutil.UniqueID, ts typeutil.Timestamp) ([]typeutil.UniqueID, schemapb.FieldSchema, error) {
N
neza2017 已提交
929 930 931
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()

N
neza2017 已提交
932 933 934
	if idxInfo.IndexParams == nil {
		return nil, schemapb.FieldSchema{}, fmt.Errorf("index param is nil")
	}
N
neza2017 已提交
935 936
	collID, ok := mt.collName2ID[collName]
	if !ok {
S
sunby 已提交
937
		return nil, schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
938 939 940
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
S
sunby 已提交
941
		return nil, schemapb.FieldSchema{}, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
942
	}
N
neza2017 已提交
943
	fieldSchema, err := mt.unlockGetFieldSchema(collName, fieldName)
N
neza2017 已提交
944 945 946 947
	if err != nil {
		return nil, fieldSchema, err
	}

N
neza2017 已提交
948 949
	var dupIdx typeutil.UniqueID = 0
	for _, f := range collMeta.FieldIndexes {
950 951 952 953
		if info, ok := mt.indexID2Meta[f.IndexID]; ok {
			if info.IndexName == idxInfo.IndexName {
				dupIdx = info.IndexID
				break
N
neza2017 已提交
954 955 956
			}
		}
	}
N
neza2017 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972

	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 已提交
973
		idx := &pb.FieldIndexInfo{
N
neza2017 已提交
974 975
			FiledID: fieldSchema.FieldID,
			IndexID: idxInfo.IndexID,
N
neza2017 已提交
976 977
		}
		collMeta.FieldIndexes = append(collMeta.FieldIndexes, idx)
N
neza2017 已提交
978 979 980 981
		mt.collID2Meta[collMeta.ID] = collMeta
		k1 := path.Join(CollectionMetaPrefix, strconv.FormatInt(collMeta.ID, 10))
		v1 := proto.MarshalTextString(&collMeta)

N
neza2017 已提交
982 983
		mt.indexID2Meta[idx.IndexID] = *idxInfo
		k2 := path.Join(IndexMetaPrefix, strconv.FormatInt(idx.IndexID, 10))
Z
zhenshan.cao 已提交
984
		v2 := proto.MarshalTextString(idxInfo)
N
neza2017 已提交
985 986
		meta := map[string]string{k1: v1, k2: v2}

N
neza2017 已提交
987 988 989 990 991 992 993 994
		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
		}
C
congqixia 已提交
995
		err = mt.client.MultiSave(meta, ts)
N
neza2017 已提交
996
		if err != nil {
997 998
			log.Error("SnapShotKV MultiSave fail", zap.Error(err))
			panic("SnapShotKV MultiSave fail")
N
neza2017 已提交
999
		}
N
neza2017 已提交
1000 1001 1002 1003 1004 1005 1006
	} 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 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
			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
			}

C
congqixia 已提交
1017
			err = mt.client.MultiSave(meta, ts)
N
neza2017 已提交
1018
			if err != nil {
1019 1020
				log.Error("SnapShotKV MultiSave fail", zap.Error(err))
				panic("SnapShotKV MultiSave fail")
N
neza2017 已提交
1021 1022
			}
		}
N
neza2017 已提交
1023 1024
	}

N
neza2017 已提交
1025
	rstID := make([]typeutil.UniqueID, 0, 16)
1026 1027 1028
	for _, segID := range segIDs {
		if exist := mt.unlockIsSegmentIndexed(segID, &fieldSchema, idxInfo.IndexParams); !exist {
			rstID = append(rstID, segID)
N
neza2017 已提交
1029 1030 1031 1032 1033
		}
	}
	return rstID, fieldSchema, nil
}

1034
func (mt *metaTable) GetIndexByName(collName, indexName string) (pb.CollectionInfo, []pb.IndexInfo, error) {
N
neza2017 已提交
1035
	mt.ddLock.RLock()
S
sunby 已提交
1036
	defer mt.ddLock.RUnlock()
N
neza2017 已提交
1037 1038 1039

	collID, ok := mt.collName2ID[collName]
	if !ok {
1040
		return pb.CollectionInfo{}, nil, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
1041 1042 1043
	}
	collMeta, ok := mt.collID2Meta[collID]
	if !ok {
1044
		return pb.CollectionInfo{}, nil, fmt.Errorf("collection %s not found", collName)
N
neza2017 已提交
1045 1046
	}

N
neza2017 已提交
1047
	rstIndex := make([]pb.IndexInfo, 0, len(collMeta.FieldIndexes))
Z
zhenshan.cao 已提交
1048
	for _, idx := range collMeta.FieldIndexes {
1049 1050
		idxInfo, ok := mt.indexID2Meta[idx.IndexID]
		if !ok {
1051
			return pb.CollectionInfo{}, nil, fmt.Errorf("index id = %d not found", idx.IndexID)
1052 1053 1054
		}
		if indexName == "" || idxInfo.IndexName == indexName {
			rstIndex = append(rstIndex, idxInfo)
N
neza2017 已提交
1055 1056
		}
	}
1057
	return collMeta, rstIndex, nil
N
neza2017 已提交
1058
}
B
bigsheeper 已提交
1059 1060 1061

func (mt *metaTable) GetIndexByID(indexID typeutil.UniqueID) (*pb.IndexInfo, error) {
	mt.ddLock.RLock()
S
sunby 已提交
1062
	defer mt.ddLock.RUnlock()
B
bigsheeper 已提交
1063 1064 1065

	indexInfo, ok := mt.indexID2Meta[indexID]
	if !ok {
S
sunby 已提交
1066
		return nil, fmt.Errorf("cannot find index, id = %d", indexID)
B
bigsheeper 已提交
1067 1068 1069
	}
	return &indexInfo, nil
}
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095

func (mt *metaTable) dupMeta() (
	map[typeutil.UniqueID]pb.CollectionInfo,
	map[typeutil.UniqueID]map[typeutil.UniqueID]pb.SegmentIndexInfo,
	map[typeutil.UniqueID]pb.IndexInfo,
) {
	mt.ddLock.RLock()
	defer mt.ddLock.RUnlock()

	collID2Meta := map[typeutil.UniqueID]pb.CollectionInfo{}
	segID2IndexMeta := map[typeutil.UniqueID]map[typeutil.UniqueID]pb.SegmentIndexInfo{}
	indexID2Meta := map[typeutil.UniqueID]pb.IndexInfo{}
	for k, v := range mt.collID2Meta {
		collID2Meta[k] = v
	}
	for k, v := range mt.segID2IndexMeta {
		segID2IndexMeta[k] = map[typeutil.UniqueID]pb.SegmentIndexInfo{}
		for k2, v2 := range v {
			segID2IndexMeta[k][k2] = v2
		}
	}
	for k, v := range mt.indexID2Meta {
		indexID2Meta[k] = v
	}
	return collID2Meta, segID2IndexMeta, indexID2Meta
}
Y
Yusup 已提交
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

func (mt *metaTable) AddAlias(collectionAlias string, collectionName string,
	ts typeutil.Timestamp, ddOpStr func(ts typeutil.Timestamp) (string, error)) error {
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
	if _, ok := mt.collAlias2ID[collectionAlias]; ok {
		return fmt.Errorf("duplicate collection alias, alias = %s", collectionAlias)
	}

	if _, ok := mt.collName2ID[collectionAlias]; ok {
		return fmt.Errorf("collection alias collides with existing collection name. collection = %s, alias = %s", collectionAlias, collectionAlias)
	}

	id, ok := mt.collName2ID[collectionName]
	if !ok {
		return fmt.Errorf("aliased collection name does not exist, name = %s", collectionName)
	}
	mt.collAlias2ID[collectionAlias] = id

	meta := make(map[string]string)
	addition := mt.getAdditionKV(ddOpStr, meta)
	saveAlias := func(ts typeutil.Timestamp) (string, string, error) {
		k1 := fmt.Sprintf("%s/%s", CollectionAliasMetaPrefix, collectionAlias)
		v1 := proto.MarshalTextString(&pb.CollectionInfo{ID: id, Schema: &schemapb.CollectionSchema{Name: collectionAlias}})
		meta[k1] = v1
		return k1, v1, nil
	}

	err := mt.client.MultiSave(meta, ts, addition, saveAlias)
	if err != nil {
		log.Error("SnapShotKV MultiSave fail", zap.Error(err))
		panic("SnapShotKV MultiSave fail")
	}
	return nil
}

func (mt *metaTable) DeleteAlias(collectionAlias string, ts typeutil.Timestamp, ddOpStr func(ts typeutil.Timestamp) (string, error)) error {
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
	if _, ok := mt.collAlias2ID[collectionAlias]; !ok {
		return fmt.Errorf("alias does not exist, alias = %s", collectionAlias)
	}
	delete(mt.collAlias2ID, collectionAlias)

	delMetakeys := []string{
		fmt.Sprintf("%s/%s", CollectionAliasMetaPrefix, collectionAlias),
	}
	meta := make(map[string]string)
	addition := mt.getAdditionKV(ddOpStr, meta)
	err := mt.client.MultiSaveAndRemoveWithPrefix(meta, delMetakeys, ts, addition)
	if err != nil {
		log.Error("SnapShotKV MultiSave fail", zap.Error(err))
		panic("SnapShotKV MultiSave fail")
	}
	return nil
}

func (mt *metaTable) AlterAlias(collectionAlias string, collectionName string, ts typeutil.Timestamp, ddOpStr func(ts typeutil.Timestamp) (string, error)) error {
	mt.ddLock.Lock()
	defer mt.ddLock.Unlock()
	if _, ok := mt.collAlias2ID[collectionAlias]; !ok {
		return fmt.Errorf("alias does not exist, alias = %s", collectionAlias)
	}

	id, ok := mt.collName2ID[collectionName]
	if !ok {
		return fmt.Errorf("aliased collection name does not exist, name = %s", collectionName)
	}
	mt.collAlias2ID[collectionAlias] = id
	meta := make(map[string]string)
	addition := mt.getAdditionKV(ddOpStr, meta)
	alterAlias := func(ts typeutil.Timestamp) (string, string, error) {
		k1 := fmt.Sprintf("%s/%s", CollectionAliasMetaPrefix, collectionAlias)
		v1 := proto.MarshalTextString(&pb.CollectionInfo{ID: id, Schema: &schemapb.CollectionSchema{Name: collectionAlias}})
		meta[k1] = v1
		return k1, v1, nil
	}

	err := mt.client.MultiSave(meta, ts, addition, alterAlias)
	if err != nil {
		log.Error("SnapShotKV MultiSave fail", zap.Error(err))
		panic("SnapShotKV MultiSave fail")
	}
	return nil
}