import_manager.go 39.0 KB
Newer Older
G
groot 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Licensed to the LF AI & Data foundation under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.

package rootcoord

import (
	"context"
	"errors"
22
	"fmt"
23
	"sort"
G
groot 已提交
24
	"strconv"
25
	"strings"
G
groot 已提交
26 27 28
	"sync"
	"time"

29
	"github.com/golang/protobuf/proto"
S
SimFG 已提交
30 31
	"github.com/milvus-io/milvus-proto/go-api/commonpb"
	"github.com/milvus-io/milvus-proto/go-api/milvuspb"
32
	"github.com/milvus-io/milvus/internal/kv"
G
groot 已提交
33 34 35
	"github.com/milvus-io/milvus/internal/log"
	"github.com/milvus-io/milvus/internal/proto/datapb"
	"github.com/milvus-io/milvus/internal/proto/rootcoordpb"
G
groot 已提交
36
	"github.com/milvus-io/milvus/internal/util/importutil"
37
	"github.com/milvus-io/milvus/internal/util/typeutil"
38
	"github.com/samber/lo"
G
groot 已提交
39 40 41 42
	"go.uber.org/zap"
)

const (
43
	delimiter = "/"
G
groot 已提交
44 45
)

46
// checkPendingTasksInterval is the default interval to check and send out pending tasks,
47 48 49
// default 60*1000 milliseconds (1 minute).
var checkPendingTasksInterval = 60 * 1000

50 51 52 53 54
// cleanUpLoopInterval is the default interval to (1) loop through all in memory tasks and expire old ones and (2) loop
// through all failed import tasks, and mark segments created by these tasks as `dropped`.
// default 5*60*1000 milliseconds (5 minutes)
var cleanUpLoopInterval = 5 * 60 * 1000

55
// flipPersistedTaskInterval is the default interval to loop through tasks and check if their states needs to be
56
// flipped/updated from `ImportPersisted` to `ImportCompleted`.
57 58 59 60
// default 2 * 1000 milliseconds (2 seconds)
// TODO: Make this configurable.
var flipPersistedTaskInterval = 2 * 1000

G
groot 已提交
61 62
// importManager manager for import tasks
type importManager struct {
63
	ctx       context.Context // reserved
64
	taskStore kv.TxnKV        // Persistent task info storage.
65
	busyNodes map[int64]int64 // Set of all current working DataNode IDs and related task create timestamp.
G
groot 已提交
66

67
	// TODO: Make pendingTask a map to improve look up performance.
68 69 70 71 72 73 74
	pendingTasks  []*datapb.ImportTaskInfo         // pending tasks
	workingTasks  map[int64]*datapb.ImportTaskInfo // in-progress tasks
	pendingLock   sync.RWMutex                     // lock pending task list
	workingLock   sync.RWMutex                     // lock working task map
	busyNodesLock sync.RWMutex                     // lock for working nodes.
	lastReqID     int64                            // for generating a unique ID for import request

75 76
	startOnce sync.Once

77 78 79
	idAllocator               func(count uint32) (typeutil.UniqueID, typeutil.UniqueID, error)
	callImportService         func(ctx context.Context, req *datapb.ImportTaskRequest) (*datapb.ImportTaskResponse, error)
	getCollectionName         func(collID, partitionID typeutil.UniqueID) (string, string, error)
80
	callGetSegmentStates      func(ctx context.Context, req *datapb.GetSegmentStatesRequest) (*datapb.GetSegmentStatesResponse, error)
81
	callUnsetIsImportingState func(context.Context, *datapb.UnsetIsImportingStateRequest) (*commonpb.Status, error)
G
groot 已提交
82 83 84
}

// newImportManager helper function to create a importManager
85
func newImportManager(ctx context.Context, client kv.TxnKV,
86
	idAlloc func(count uint32) (typeutil.UniqueID, typeutil.UniqueID, error),
87
	importService func(ctx context.Context, req *datapb.ImportTaskRequest) (*datapb.ImportTaskResponse, error),
88
	getSegmentStates func(ctx context.Context, req *datapb.GetSegmentStatesRequest) (*datapb.GetSegmentStatesResponse, error),
89 90
	getCollectionName func(collID, partitionID typeutil.UniqueID) (string, string, error),
	unsetIsImportingState func(context.Context, *datapb.UnsetIsImportingStateRequest) (*commonpb.Status, error)) *importManager {
G
groot 已提交
91
	mgr := &importManager{
92 93
		ctx:                       ctx,
		taskStore:                 client,
94
		pendingTasks:              make([]*datapb.ImportTaskInfo, 0, Params.RootCoordCfg.ImportMaxPendingTaskCount.GetAsInt()), // currently task queue max size is 32
95
		workingTasks:              make(map[int64]*datapb.ImportTaskInfo),
96
		busyNodes:                 make(map[int64]int64),
97 98 99 100 101 102
		pendingLock:               sync.RWMutex{},
		workingLock:               sync.RWMutex{},
		busyNodesLock:             sync.RWMutex{},
		lastReqID:                 0,
		idAllocator:               idAlloc,
		callImportService:         importService,
103
		callGetSegmentStates:      getSegmentStates,
104 105
		getCollectionName:         getCollectionName,
		callUnsetIsImportingState: unsetIsImportingState,
G
groot 已提交
106 107 108 109
	}
	return mgr
}

110 111
func (m *importManager) init(ctx context.Context) {
	m.startOnce.Do(func() {
112 113 114 115 116
		// Read tasks from Etcd and save them as pending tasks and mark them as failed.
		if _, err := m.loadFromTaskStore(true); err != nil {
			log.Error("importManager init failed, read tasks from Etcd failed, about to panic")
			panic(err)
		}
117
		// Send out tasks to dataCoord.
118 119 120
		if err := m.sendOutTasks(ctx); err != nil {
			log.Error("importManager init failed, send out tasks to dataCoord failed")
		}
121
	})
G
groot 已提交
122 123
}

124 125 126 127 128 129 130 131 132 133 134
// sendOutTasksLoop periodically calls `sendOutTasks` to process left over pending tasks.
func (m *importManager) sendOutTasksLoop(wg *sync.WaitGroup) {
	defer wg.Done()
	ticker := time.NewTicker(time.Duration(checkPendingTasksInterval) * time.Millisecond)
	defer ticker.Stop()
	for {
		select {
		case <-m.ctx.Done():
			log.Debug("import manager context done, exit check sendOutTasksLoop")
			return
		case <-ticker.C:
135 136 137
			if err := m.sendOutTasks(m.ctx); err != nil {
				log.Error("importManager sendOutTasksLoop fail to send out tasks")
			}
138 139 140 141
		}
	}
}

142 143
// flipTaskStateLoop periodically calls `flipTaskState` to check if states of the tasks need to be updated.
func (m *importManager) flipTaskStateLoop(wg *sync.WaitGroup) {
144
	defer wg.Done()
145 146
	flipPersistedTicker := time.NewTicker(time.Duration(flipPersistedTaskInterval) * time.Millisecond)
	defer flipPersistedTicker.Stop()
147 148 149
	for {
		select {
		case <-m.ctx.Done():
150
			log.Debug("import manager context done, exit check flipTaskStateLoop")
151
			return
152
		case <-flipPersistedTicker.C:
G
groot 已提交
153
			// log.Debug("start trying to flip ImportPersisted task")
154 155 156
			if err := m.loadAndFlipPersistedTasks(m.ctx); err != nil {
				log.Error("failed to flip ImportPersisted task", zap.Error(err))
			}
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
		}
	}
}

// cleanupLoop starts a loop that checks and expires old tasks every `cleanUpLoopInterval` seconds.
// There are two types of tasks to clean up:
// (1) pending tasks or working tasks that existed for over `ImportTaskExpiration` seconds, these tasks will be
// removed from memory.
// (2) any import tasks that has been created over `ImportTaskRetention` seconds ago, these tasks will be removed from Etcd.
// cleanupLoop also periodically calls removeBadImportSegments to remove bad import segments.
func (m *importManager) cleanupLoop(wg *sync.WaitGroup) {
	defer wg.Done()
	ticker := time.NewTicker(time.Duration(cleanUpLoopInterval) * time.Millisecond)
	defer ticker.Stop()
	for {
		select {
		case <-m.ctx.Done():
			log.Debug("(in cleanupLoop) import manager context done, exit cleanupLoop")
			return
		case <-ticker.C:
			log.Debug("(in cleanupLoop) trying to expire old tasks from memory and Etcd")
			m.expireOldTasksFromMem()
			m.expireOldTasksFromEtcd()
			log.Debug("(in cleanupLoop) start removing bad import segments")
			m.removeBadImportSegments(m.ctx)
182 183
			log.Debug("(in cleanupLoop) start cleaning hanging busy DataNode")
			m.releaseHangingBusyDataNode()
184 185 186 187
		}
	}
}

188
// sendOutTasks pushes all pending tasks to DataCoord, gets DataCoord response and re-add these tasks as working tasks.
189
func (m *importManager) sendOutTasks(ctx context.Context) error {
G
groot 已提交
190
	m.pendingLock.Lock()
191
	m.busyNodesLock.Lock()
G
groot 已提交
192
	defer m.pendingLock.Unlock()
193
	defer m.busyNodesLock.Unlock()
G
groot 已提交
194

195 196
	// Trigger Import() action to DataCoord.
	for len(m.pendingTasks) > 0 {
197
		log.Debug("try to send out pending tasks", zap.Int("task_number", len(m.pendingTasks)))
G
groot 已提交
198
		task := m.pendingTasks[0]
199
		// TODO: Use ImportTaskInfo directly.
200 201 202
		it := &datapb.ImportTask{
			CollectionId: task.GetCollectionId(),
			PartitionId:  task.GetPartitionId(),
203
			ChannelNames: task.GetChannelNames(),
204 205
			TaskId:       task.GetId(),
			Files:        task.GetFiles(),
206
			Infos:        task.GetInfos(),
G
groot 已提交
207 208
		}

209 210 211 212 213 214
		// Get all busy dataNodes for reference.
		var busyNodeList []int64
		for k := range m.busyNodes {
			busyNodeList = append(busyNodeList, k)
		}

215
		// Send import task to dataCoord, which will then distribute the import task to dataNode.
216
		resp, err := m.callImportService(ctx, &datapb.ImportTaskRequest{
217 218 219
			ImportTask:   it,
			WorkingNodes: busyNodeList,
		})
220 221 222 223 224
		if resp.GetStatus().GetErrorCode() != commonpb.ErrorCode_Success {
			log.Warn("import task is rejected",
				zap.Int64("task ID", it.GetTaskId()),
				zap.Any("error code", resp.GetStatus().GetErrorCode()),
				zap.String("cause", resp.GetStatus().GetReason()))
G
groot 已提交
225 226
			break
		}
227
		if err != nil {
228
			log.Warn("import task get error", zap.Error(err))
229 230
			break
		}
231 232

		// Successfully assigned dataNode for the import task. Add task to working task list and update task store.
233
		task.DatanodeId = resp.GetDatanodeId()
234
		log.Debug("import task successfully assigned to dataNode",
235
			zap.Int64("task ID", it.GetTaskId()),
236
			zap.Int64("dataNode ID", task.GetDatanodeId()))
237
		// Add new working dataNode to busyNodes.
238
		m.busyNodes[resp.GetDatanodeId()] = task.GetCreateTs()
239
		err = func() error {
G
groot 已提交
240 241
			m.workingLock.Lock()
			defer m.workingLock.Unlock()
242
			log.Debug("import task added as working task", zap.Int64("task ID", it.TaskId))
243
			task.State.StateCode = commonpb.ImportState_ImportStarted
G
groot 已提交
244
			task.StartTs = time.Now().Unix()
245 246 247 248 249 250 251
			// first update the import task into meta store and then put it into working tasks
			if err := m.persistTaskInfo(task); err != nil {
				log.Error("failed to update import task",
					zap.Int64("task ID", task.GetId()),
					zap.Error(err))
				return err
			}
252
			m.workingTasks[task.GetId()] = task
253
			return nil
G
groot 已提交
254
		}()
255 256 257 258
		if err != nil {
			return err
		}
		// Remove this task from head of pending list.
259
		m.pendingTasks = append(m.pendingTasks[:0], m.pendingTasks[1:]...)
G
groot 已提交
260 261 262 263 264
	}

	return nil
}

265
// loadAndFlipPersistedTasks checks every import task in `ImportPersisted` state and flips their import state to
266
// `ImportCompleted` if eligible.
267
func (m *importManager) loadAndFlipPersistedTasks(ctx context.Context) error {
268 269 270 271 272 273
	var importTasks []*datapb.ImportTaskInfo
	var err error
	if importTasks, err = m.loadFromTaskStore(false); err != nil {
		log.Error("failed to load from task store", zap.Error(err))
		return err
	}
274

275
	for _, task := range importTasks {
276
		// Checking if ImportPersisted --> ImportCompleted ready.
277
		if task.GetState().GetStateCode() == commonpb.ImportState_ImportPersisted {
278
			log.Info("<ImportPersisted> task found, checking if it is eligible to become <ImportCompleted>",
279
				zap.Int64("task ID", task.GetId()))
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
			importTask := m.getTaskState(task.GetId())

			// if this method failed, skip this task, try again in next round
			if err = m.flipTaskFlushedState(ctx, importTask, task.GetDatanodeId()); err != nil {
				log.Error("failed to flip task flushed state",
					zap.Int64("task ID", task.GetId()),
					zap.Error(err))
			}
		}
	}
	return nil
}

func (m *importManager) flipTaskFlushedState(ctx context.Context, importTask *milvuspb.GetImportStateResponse, dataNodeID int64) error {
	ok, err := m.checkFlushDone(ctx, importTask.GetSegmentIds())
	if err != nil {
		log.Error("an error occurred while checking flush state of segments",
			zap.Int64("task ID", importTask.GetId()),
			zap.Error(err))
		return err
	}
	if ok {
		// All segments are flushed. DataNode becomes available.
		func() {
			m.busyNodesLock.Lock()
			defer m.busyNodesLock.Unlock()
			delete(m.busyNodes, dataNodeID)
			log.Info("a DataNode is no longer busy after processing task",
				zap.Int64("dataNode ID", dataNodeID),
				zap.Int64("task ID", importTask.GetId()))

		}()
312 313 314 315
		// Unset isImporting flag.
		if m.callUnsetIsImportingState == nil {
			log.Error("callUnsetIsImportingState function of importManager is nil")
			return fmt.Errorf("failed to describe index: segment state method of import manager is nil")
316
		}
317 318 319
		_, err := m.callUnsetIsImportingState(ctx, &datapb.UnsetIsImportingStateRequest{
			SegmentIds: importTask.GetSegmentIds(),
		})
320
		if err := m.setImportTaskState(importTask.GetId(), commonpb.ImportState_ImportCompleted); err != nil {
G
groot 已提交
321
			log.Error("failed to set import task state",
322
				zap.Int64("task ID", importTask.GetId()),
G
groot 已提交
323 324 325 326 327 328 329 330 331
				zap.Any("target state", commonpb.ImportState_ImportCompleted),
				zap.Error(err))
			return err
		}
		if err != nil {
			log.Error("failed to unset importing state of all segments (could be partial failure)",
				zap.Error(err))
			return err
		}
332 333 334 335
		// Start working on new bulk insert tasks.
		if err = m.sendOutTasks(m.ctx); err != nil {
			log.Error("fail to send out import task to DataNodes",
				zap.Int64("task ID", importTask.GetId()))
G
groot 已提交
336 337 338 339 340
		}
	}
	return nil
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
// checkFlushDone checks if flush is done on given segments.
func (m *importManager) checkFlushDone(ctx context.Context, segIDs []UniqueID) (bool, error) {
	resp, err := m.callGetSegmentStates(ctx, &datapb.GetSegmentStatesRequest{
		SegmentIDs: segIDs,
	})
	if err != nil {
		log.Error("failed to get import task segment states",
			zap.Int64s("segment IDs", segIDs))
		return false, err
	}
	getSegmentStates := func(segment *datapb.SegmentStateInfo, _ int) string {
		return segment.GetState().String()
	}
	log.Debug("checking import segment states",
		zap.Strings("segment states", lo.Map(resp.GetStates(), getSegmentStates)))
	for _, states := range resp.GetStates() {
		// Flushed segment could get compacted, so only returns false if there are still importing segments.
		if states.GetState() == commonpb.SegmentState_Importing ||
			states.GetState() == commonpb.SegmentState_Sealed {
			return false, nil
		}
	}
	return true, nil
}

G
groot 已提交
366 367 368 369 370 371 372 373 374 375 376 377
func (m *importManager) isRowbased(files []string) (bool, error) {
	isRowBased := false
	for _, filePath := range files {
		_, fileType := importutil.GetFileNameAndExt(filePath)
		if fileType == importutil.JSONFileExt {
			isRowBased = true
		} else if isRowBased {
			log.Error("row-based data file type must be JSON, mixed file types is not allowed", zap.Strings("files", files))
			return isRowBased, fmt.Errorf("row-based data file type must be JSON, file type '%s' is not allowed", fileType)
		}
	}

378 379 380 381 382 383
	// for row_based, we only allow one file so that each invocation only generate a task
	if isRowBased && len(files) > 1 {
		log.Error("row-based import, only allow one JSON file each time", zap.Strings("files", files))
		return isRowBased, fmt.Errorf("row-based import, only allow one JSON file each time")
	}

G
groot 已提交
384 385 386
	return isRowBased, nil
}

387 388
// importJob processes the import request, generates import tasks, sends these tasks to DataCoord, and returns
// immediately.
389
func (m *importManager) importJob(ctx context.Context, req *milvuspb.ImportRequest, cID int64, pID int64) *milvuspb.ImportResponse {
G
groot 已提交
390
	returnErrorFunc := func(reason string) *milvuspb.ImportResponse {
G
groot 已提交
391 392 393
		return &milvuspb.ImportResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
G
groot 已提交
394
				Reason:    reason,
G
groot 已提交
395 396 397 398
			},
		}
	}

G
groot 已提交
399 400 401 402
	if req == nil || len(req.Files) == 0 {
		return returnErrorFunc("import request is empty")
	}

G
groot 已提交
403
	if m.callImportService == nil {
G
groot 已提交
404
		return returnErrorFunc("import service is not available")
G
groot 已提交
405 406 407 408 409 410
	}

	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
411
		Tasks: make([]int64, 0),
G
groot 已提交
412 413
	}

G
groot 已提交
414
	log.Debug("receive import job",
415
		zap.String("collection name", req.GetCollectionName()),
416 417
		zap.Int64("collection ID", cID),
		zap.Int64("partition ID", pID))
418
	err := func() error {
G
groot 已提交
419 420 421 422 423 424
		m.pendingLock.Lock()
		defer m.pendingLock.Unlock()

		capacity := cap(m.pendingTasks)
		length := len(m.pendingTasks)

G
groot 已提交
425 426 427 428 429
		isRowBased, err := m.isRowbased(req.GetFiles())
		if err != nil {
			return err
		}

G
groot 已提交
430
		taskCount := 1
G
groot 已提交
431
		if isRowBased {
G
groot 已提交
432 433 434
			taskCount = len(req.Files)
		}

435
		// task queue size has a limit, return error if import request contains too many data files, and skip entire job
G
groot 已提交
436
		if capacity-length < taskCount {
437
			err := fmt.Errorf("import task queue max size is %v, currently there are %v tasks is pending. Not able to execute this request with %v tasks", capacity, length, taskCount)
438 439
			log.Error(err.Error())
			return err
G
groot 已提交
440 441 442
		}

		// convert import request to import tasks
G
groot 已提交
443
		if isRowBased {
444
			// For row-based importing, each file makes a task.
G
groot 已提交
445
			taskList := make([]int64, len(req.Files))
G
groot 已提交
446
			for i := 0; i < len(req.Files); i++ {
447 448
				tID, _, err := m.idAllocator(1)
				if err != nil {
449
					log.Error("failed to allocate ID for import task", zap.Error(err))
450 451
					return err
				}
452
				newTask := &datapb.ImportTaskInfo{
453
					Id:           tID,
454
					CollectionId: cID,
455
					PartitionId:  pID,
456
					ChannelNames: req.ChannelNames,
457 458 459 460 461
					Files:        []string{req.GetFiles()[i]},
					CreateTs:     time.Now().Unix(),
					State: &datapb.ImportTaskState{
						StateCode: commonpb.ImportState_ImportPending,
					},
462
					Infos: req.Options,
G
groot 已提交
463
				}
464 465 466 467 468 469

				// Here no need to check error returned by setCollectionPartitionName(),
				// since here we always return task list to client no matter something missed.
				// We make the method setCollectionPartitionName() returns error
				// because we need to make sure coverage all the code branch in unittest case.
				_ = m.setCollectionPartitionName(cID, pID, newTask)
470
				resp.Tasks = append(resp.Tasks, newTask.GetId())
471
				taskList[i] = newTask.GetId()
472 473 474 475 476 477 478 479
				log.Info("new task created as pending task",
					zap.Int64("task ID", newTask.GetId()))
				if err := m.persistTaskInfo(newTask); err != nil {
					log.Error("failed to update import task",
						zap.Int64("task ID", newTask.GetId()),
						zap.Error(err))
					return err
				}
G
groot 已提交
480 481
				m.pendingTasks = append(m.pendingTasks, newTask)
			}
482
			log.Info("row-based import request processed", zap.Any("task IDs", taskList))
G
groot 已提交
483
		} else {
484
			// TODO: Merge duplicated code :(
G
groot 已提交
485
			// for column-based, all files is a task
486 487 488 489
			tID, _, err := m.idAllocator(1)
			if err != nil {
				return err
			}
490
			newTask := &datapb.ImportTaskInfo{
491
				Id:           tID,
492
				CollectionId: cID,
493
				PartitionId:  pID,
494
				ChannelNames: req.ChannelNames,
495 496 497 498 499
				Files:        req.GetFiles(),
				CreateTs:     time.Now().Unix(),
				State: &datapb.ImportTaskState{
					StateCode: commonpb.ImportState_ImportPending,
				},
500
				Infos: req.Options,
G
groot 已提交
501
			}
502 503 504 505 506
			// Here no need to check error returned by setCollectionPartitionName(),
			// since here we always return task list to client no matter something missed.
			// We make the method setCollectionPartitionName() returns error
			// because we need to make sure coverage all the code branch in unittest case.
			_ = m.setCollectionPartitionName(cID, pID, newTask)
507
			resp.Tasks = append(resp.Tasks, newTask.GetId())
508 509 510 511 512 513 514 515
			log.Info("new task created as pending task",
				zap.Int64("task ID", newTask.GetId()))
			if err := m.persistTaskInfo(newTask); err != nil {
				log.Error("failed to update import task",
					zap.Int64("task ID", newTask.GetId()),
					zap.Error(err))
				return err
			}
G
groot 已提交
516
			m.pendingTasks = append(m.pendingTasks, newTask)
517 518
			log.Info("column-based import request processed",
				zap.Int64("task ID", newTask.GetId()))
G
groot 已提交
519
		}
520
		return nil
G
groot 已提交
521
	}()
522
	if err != nil {
G
groot 已提交
523
		return returnErrorFunc(err.Error())
524
	}
525 526
	if sendOutTasksErr := m.sendOutTasks(ctx); sendOutTasksErr != nil {
		log.Error("fail to send out tasks", zap.Error(sendOutTasksErr))
527
	}
528
	return resp
529 530
}

531
// updateTaskInfo updates the task's state in in-memory working tasks list and in task store, given ImportResult
532
// result. It returns the ImportTaskInfo of the given task.
533
func (m *importManager) updateTaskInfo(ir *rootcoordpb.ImportResult) (*datapb.ImportTaskInfo, error) {
534 535
	if ir == nil {
		return nil, errors.New("import result is nil")
G
groot 已提交
536
	}
537
	log.Debug("import manager update task import result", zap.Int64("taskID", ir.GetTaskId()))
G
groot 已提交
538

G
groot 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
	updatedInfo, err := func() (*datapb.ImportTaskInfo, error) {
		found := false
		var v *datapb.ImportTaskInfo
		m.workingLock.Lock()
		defer m.workingLock.Unlock()
		ok := false
		var toPersistImportTaskInfo *datapb.ImportTaskInfo

		if v, ok = m.workingTasks[ir.GetTaskId()]; ok {
			// If the task has already been marked failed. Prevent further state updating and return an error.
			if v.GetState().GetStateCode() == commonpb.ImportState_ImportFailed ||
				v.GetState().GetStateCode() == commonpb.ImportState_ImportFailedAndCleaned {
				log.Warn("trying to update an already failed task which will end up being a no-op")
				return nil, errors.New("trying to update an already failed task " + strconv.FormatInt(ir.GetTaskId(), 10))
			}
			found = true

			// Meta persist should be done before memory objs change.
			toPersistImportTaskInfo = cloneImportTaskInfo(v)
			toPersistImportTaskInfo.State.StateCode = ir.GetState()
559 560 561 562 563 564
			// if is started state, append the new created segment id
			if v.GetState().GetStateCode() == commonpb.ImportState_ImportStarted {
				toPersistImportTaskInfo.State.Segments = append(toPersistImportTaskInfo.State.Segments, ir.GetSegments()...)
			} else {
				toPersistImportTaskInfo.State.Segments = ir.GetSegments()
			}
G
groot 已提交
565 566 567 568 569 570
			toPersistImportTaskInfo.State.RowCount = ir.GetRowCount()
			toPersistImportTaskInfo.State.RowIds = ir.GetAutoIds()
			for _, kv := range ir.GetInfos() {
				if kv.GetKey() == importutil.FailedReason {
					toPersistImportTaskInfo.State.ErrorMessage = kv.GetValue()
					break
571 572 573
				} else if kv.GetKey() == importutil.PersistTimeCost ||
					kv.GetKey() == importutil.ProgressPercent {
					importutil.UpdateKVInfo(&toPersistImportTaskInfo.Infos, kv.GetKey(), kv.GetValue())
G
groot 已提交
574 575
				}
			}
576 577
			log.Info("importManager update task info", zap.Any("toPersistImportTaskInfo", toPersistImportTaskInfo))

G
groot 已提交
578 579 580 581 582 583
			// Update task in task store.
			if err := m.persistTaskInfo(toPersistImportTaskInfo); err != nil {
				log.Error("failed to update import task",
					zap.Int64("task ID", v.GetId()),
					zap.Error(err))
				return nil, err
G
groot 已提交
584
			}
G
groot 已提交
585
			m.workingTasks[ir.GetTaskId()] = toPersistImportTaskInfo
G
groot 已提交
586
		}
G
groot 已提交
587 588 589 590

		if !found {
			log.Debug("import manager update task import result failed", zap.Int64("task ID", ir.GetTaskId()))
			return nil, errors.New("failed to update import task, ID not found: " + strconv.FormatInt(ir.TaskId, 10))
591
		}
G
groot 已提交
592 593 594 595 596 597

		return toPersistImportTaskInfo, nil
	}()

	if err != nil {
		return nil, err
598
	}
G
groot 已提交
599
	return updatedInfo, nil
G
groot 已提交
600 601
}

602 603 604
// setImportTaskState sets the task state of an import task. Changes to the import task state will be persisted.
func (m *importManager) setImportTaskState(taskID int64, targetState commonpb.ImportState) error {
	return m.setImportTaskStateAndReason(taskID, targetState, "")
605 606
}

607 608 609 610
// setImportTaskStateAndReason sets the task state and error message of an import task. Changes to the import task state
// will be persisted.
func (m *importManager) setImportTaskStateAndReason(taskID int64, targetState commonpb.ImportState, errReason string) error {
	log.Info("trying to set the import state of an import task",
611
		zap.Int64("task ID", taskID),
612 613 614 615 616 617 618 619 620
		zap.Any("target state", targetState))
	found := false
	m.pendingLock.Lock()
	for taskIndex, t := range m.pendingTasks {
		if taskID == t.Id {
			found = true
			// Meta persist should be done before memory objs change.
			toPersistImportTaskInfo := cloneImportTaskInfo(t)
			toPersistImportTaskInfo.State.StateCode = targetState
621 622 623
			if targetState == commonpb.ImportState_ImportCompleted {
				importutil.UpdateKVInfo(&toPersistImportTaskInfo.Infos, importutil.ProgressPercent, "100")
			}
624 625 626 627 628 629 630 631 632 633
			tryUpdateErrMsg(errReason, toPersistImportTaskInfo)
			// Update task in task store.
			if err := m.persistTaskInfo(toPersistImportTaskInfo); err != nil {
				return err
			}
			m.pendingTasks[taskIndex] = toPersistImportTaskInfo
			break
		}
	}
	m.pendingLock.Unlock()
634 635

	m.workingLock.Lock()
636 637 638 639 640
	if v, ok := m.workingTasks[taskID]; ok {
		found = true
		// Meta persist should be done before memory objs change.
		toPersistImportTaskInfo := cloneImportTaskInfo(v)
		toPersistImportTaskInfo.State.StateCode = targetState
641 642 643
		if targetState == commonpb.ImportState_ImportCompleted {
			importutil.UpdateKVInfo(&toPersistImportTaskInfo.Infos, importutil.ProgressPercent, "100")
		}
644
		tryUpdateErrMsg(errReason, toPersistImportTaskInfo)
645
		// Update task in task store.
646 647 648 649
		if err := m.persistTaskInfo(toPersistImportTaskInfo); err != nil {
			return err
		}
		m.workingTasks[taskID] = toPersistImportTaskInfo
650 651 652
	}
	m.workingLock.Unlock()

653 654 655 656 657 658 659 660 661 662
	// If task is not found in memory, try updating in Etcd.
	var v string
	var err error
	if !found {
		if v, err = m.taskStore.Load(BuildImportTaskKey(taskID)); err == nil && v != "" {
			ti := &datapb.ImportTaskInfo{}
			if err := proto.Unmarshal([]byte(v), ti); err != nil {
				log.Error("failed to unmarshal proto", zap.String("taskInfo", v), zap.Error(err))
			} else {
				toPersistImportTaskInfo := cloneImportTaskInfo(ti)
663
				toPersistImportTaskInfo.State.StateCode = targetState
664 665 666
				if targetState == commonpb.ImportState_ImportCompleted {
					importutil.UpdateKVInfo(&toPersistImportTaskInfo.Infos, importutil.ProgressPercent, "100")
				}
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
				tryUpdateErrMsg(errReason, toPersistImportTaskInfo)
				// Update task in task store.
				if err := m.persistTaskInfo(toPersistImportTaskInfo); err != nil {
					return err
				}
				found = true
			}
		} else {
			log.Warn("failed to load task info from Etcd",
				zap.String("value", v),
				zap.Error(err))
		}
	}

	if !found {
		return errors.New("failed to update import task state, ID not found: " + strconv.FormatInt(taskID, 10))
683 684 685 686
	}
	return nil
}

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
func (m *importManager) setCollectionPartitionName(colID, partID int64, task *datapb.ImportTaskInfo) error {
	if m.getCollectionName != nil {
		colName, partName, err := m.getCollectionName(colID, partID)
		if err == nil {
			task.CollectionName = colName
			task.PartitionName = partName
			return nil
		}
		log.Error("failed to setCollectionPartitionName",
			zap.Int64("collection ID", colID),
			zap.Int64("partition ID", partID),
			zap.Error(err))
	}
	return errors.New("failed to setCollectionPartitionName for import task")
}

func (m *importManager) copyTaskInfo(input *datapb.ImportTaskInfo, output *milvuspb.GetImportStateResponse) {
	output.Status = &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_Success,
	}
G
groot 已提交
707

708 709 710 711 712 713 714
	output.Id = input.GetId()
	output.CollectionId = input.GetCollectionId()
	output.State = input.GetState().GetStateCode()
	output.RowCount = input.GetState().GetRowCount()
	output.IdList = input.GetState().GetRowIds()
	output.SegmentIds = input.GetState().GetSegments()
	output.CreateTs = input.GetCreateTs()
G
groot 已提交
715 716 717
	output.Infos = append(output.Infos, &commonpb.KeyValuePair{Key: importutil.Files, Value: strings.Join(input.GetFiles(), ",")})
	output.Infos = append(output.Infos, &commonpb.KeyValuePair{Key: importutil.CollectionName, Value: input.GetCollectionName()})
	output.Infos = append(output.Infos, &commonpb.KeyValuePair{Key: importutil.PartitionName, Value: input.GetPartitionName()})
718
	output.Infos = append(output.Infos, &commonpb.KeyValuePair{
G
groot 已提交
719
		Key:   importutil.FailedReason,
720 721
		Value: input.GetState().GetErrorMessage(),
	})
G
groot 已提交
722
	output.Infos = append(output.Infos, input.Infos...)
723 724
}

725 726
// getTaskState looks for task with the given ID and returns its import state.
func (m *importManager) getTaskState(tID int64) *milvuspb.GetImportStateResponse {
G
groot 已提交
727 728 729 730 731
	resp := &milvuspb.GetImportStateResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    "import task id doesn't exist",
		},
732
		Infos: make([]*commonpb.KeyValuePair, 0),
G
groot 已提交
733
	}
734
	// (1) Search in pending tasks list.
G
groot 已提交
735
	found := false
736 737 738 739 740 741
	m.pendingLock.Lock()
	for _, t := range m.pendingTasks {
		if tID == t.Id {
			m.copyTaskInfo(t, resp)
			found = true
			break
G
groot 已提交
742
		}
743 744
	}
	m.pendingLock.Unlock()
G
groot 已提交
745 746 747
	if found {
		return resp
	}
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
	// (2) Search in working tasks map.
	m.workingLock.Lock()
	if v, ok := m.workingTasks[tID]; ok {
		found = true
		m.copyTaskInfo(v, resp)
	}
	m.workingLock.Unlock()
	if found {
		return resp
	}
	// (3) Search in Etcd.
	if v, err := m.taskStore.Load(BuildImportTaskKey(tID)); err == nil && v != "" {
		ti := &datapb.ImportTaskInfo{}
		if err := proto.Unmarshal([]byte(v), ti); err != nil {
			log.Error("failed to unmarshal proto", zap.String("taskInfo", v), zap.Error(err))
		} else {
			m.copyTaskInfo(ti, resp)
765
			found = true
G
groot 已提交
766
		}
767 768 769 770 771
	} else {
		log.Warn("failed to load task info from Etcd",
			zap.String("value", v),
			zap.Error(err))
	}
772
	if found {
773
		log.Info("getting import task state", zap.Int64("task ID", tID), zap.Any("state", resp.State), zap.Int64s("segment", resp.SegmentIds))
774
		return resp
G
groot 已提交
775
	}
776
	log.Debug("get import task state failed", zap.Int64("taskID", tID))
G
groot 已提交
777 778
	return resp
}
779

780 781 782 783 784
// loadFromTaskStore loads task info from task store (Etcd).
// loadFromTaskStore also adds these tasks as pending import tasks, and mark
// other in-progress tasks as failed, when `load2Mem` is set to `true`.
// loadFromTaskStore instead returns a list of all import tasks if `load2Mem` is set to `false`.
func (m *importManager) loadFromTaskStore(load2Mem bool) ([]*datapb.ImportTaskInfo, error) {
G
groot 已提交
785
	// log.Debug("import manager starts loading from Etcd")
786
	_, v, err := m.taskStore.LoadWithPrefix(Params.RootCoordCfg.ImportTaskSubPath.GetValue())
787
	if err != nil {
788
		log.Error("import manager failed to load from Etcd", zap.Error(err))
789
		return nil, err
790
	}
791
	var taskList []*datapb.ImportTaskInfo
G
groot 已提交
792

793 794 795
	for i := range v {
		ti := &datapb.ImportTaskInfo{}
		if err := proto.Unmarshal([]byte(v[i]), ti); err != nil {
796
			log.Error("failed to unmarshal proto", zap.String("taskInfo", v[i]), zap.Error(err))
797 798 799
			// Ignore bad protos.
			continue
		}
G
groot 已提交
800

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
		if load2Mem {
			// Put pending tasks back to pending task list.
			if ti.GetState().GetStateCode() == commonpb.ImportState_ImportPending {
				log.Info("task has been reloaded as a pending task", zap.Int64("task ID", ti.GetId()))
				m.pendingLock.Lock()
				m.pendingTasks = append(m.pendingTasks, ti)
				m.pendingLock.Unlock()
			} else {
				// other non-failed and non-completed tasks should be marked failed, so the bad s egments
				// can be cleaned up in `removeBadImportSegmentsLoop`.
				if ti.GetState().GetStateCode() != commonpb.ImportState_ImportFailed &&
					ti.GetState().GetStateCode() != commonpb.ImportState_ImportFailedAndCleaned &&
					ti.GetState().GetStateCode() != commonpb.ImportState_ImportCompleted {
					ti.State.StateCode = commonpb.ImportState_ImportFailed
					if ti.GetState().GetErrorMessage() == "" {
						ti.State.ErrorMessage = "task marked failed as service restarted"
					} else {
						ti.State.ErrorMessage = fmt.Sprintf("%s; task marked failed as service restarted",
							ti.GetState().GetErrorMessage())
					}
					if err := m.persistTaskInfo(ti); err != nil {
						log.Error("failed to mark an old task as expired",
							zap.Int64("task ID", ti.GetId()),
							zap.Error(err))
					}
					log.Info("task has been marked failed while reloading",
						zap.Int64("task ID", ti.GetId()))
				}
			}
830
		} else {
831
			taskList = append(taskList, ti)
832 833
		}
	}
834
	return taskList, nil
835 836
}

837 838 839 840 841 842 843 844
// persistTaskInfo stores or updates the import task info in Etcd.
func (m *importManager) persistTaskInfo(ti *datapb.ImportTaskInfo) error {
	log.Info("updating import task info in Etcd", zap.Int64("task ID", ti.GetId()))
	var taskInfo []byte
	var err error
	if taskInfo, err = proto.Marshal(ti); err != nil {
		log.Error("failed to marshall task info proto",
			zap.Int64("task ID", ti.GetId()),
845
			zap.Error(err))
846 847
		return err
	}
848 849 850
	if err = m.taskStore.Save(BuildImportTaskKey(ti.GetId()), string(taskInfo)); err != nil {
		log.Error("failed to update import task info in Etcd",
			zap.Int64("task ID", ti.GetId()),
851
			zap.Error(err))
852 853 854 855 856
		return err
	}
	return nil
}

857 858 859 860 861 862 863 864
// yieldTaskInfo removes the task info from Etcd.
func (m *importManager) yieldTaskInfo(tID int64) error {
	log.Info("removing import task info from Etcd",
		zap.Int64("task ID", tID))
	if err := m.taskStore.Remove(BuildImportTaskKey(tID)); err != nil {
		log.Error("failed to update import task info in Etcd",
			zap.Int64("task ID", tID),
			zap.Error(err))
865 866 867 868 869
		return err
	}
	return nil
}

870 871
// expireOldTasks removes expired tasks from memory.
func (m *importManager) expireOldTasksFromMem() {
G
groot 已提交
872 873 874 875
	// no need to expire pending tasks. With old working tasks finish or turn into expired, datanodes back to idle,
	// let the sendOutTasksLoop() push pending tasks into datanodes.

	// expire old working tasks.
876 877 878 879
	func() {
		m.workingLock.Lock()
		defer m.workingLock.Unlock()
		for _, v := range m.workingTasks {
880
			taskExpiredAndStateUpdated := false
881
			if v.GetState().GetStateCode() != commonpb.ImportState_ImportCompleted && taskExpired(v) {
G
groot 已提交
882 883 884
				log.Info("a working task has expired and will be marked as failed",
					zap.Int64("task ID", v.GetId()),
					zap.Int64("startTs", v.GetStartTs()),
885
					zap.Float64("ImportTaskExpiration", Params.RootCoordCfg.ImportTaskExpiration.GetAsFloat()))
886 887
				taskID := v.GetId()
				m.workingLock.Unlock()
888 889 890 891
				// Remove DataNode from busy node list, so it can serve other tasks again.
				m.busyNodesLock.Lock()
				delete(m.busyNodes, v.GetDatanodeId())
				m.busyNodesLock.Unlock()
G
groot 已提交
892

893 894 895 896 897 898 899 900 901 902 903 904
				if err := m.setImportTaskStateAndReason(taskID, commonpb.ImportState_ImportFailed,
					"the import task has timed out"); err != nil {
					log.Error("failed to set import task state",
						zap.Int64("task ID", taskID),
						zap.Any("target state", commonpb.ImportState_ImportFailed))
				} else {
					taskExpiredAndStateUpdated = true
				}
				m.workingLock.Lock()
				if taskExpiredAndStateUpdated {
					// Remove this task from memory.
					delete(m.workingTasks, v.GetId())
905
				}
906 907 908 909 910
			}
		}
	}()
}

911 912 913 914 915
// expireOldTasksFromEtcd removes tasks from Etcd that are over `ImportTaskRetention` seconds old.
func (m *importManager) expireOldTasksFromEtcd() {
	var vs []string
	var err error
	// Collect all import task records.
916
	if _, vs, err = m.taskStore.LoadWithPrefix(Params.RootCoordCfg.ImportTaskSubPath.GetValue()); err != nil {
917 918 919 920 921 922 923 924 925 926 927 928 929
		log.Error("failed to load import tasks from Etcd during task cleanup")
		return
	}
	// Loop through all import tasks in Etcd and look for the ones that have passed retention period.
	for _, val := range vs {
		ti := &datapb.ImportTaskInfo{}
		if err := proto.Unmarshal([]byte(val), ti); err != nil {
			log.Error("failed to unmarshal proto", zap.String("taskInfo", val), zap.Error(err))
			// Ignore bad protos. This is just a cleanup task, so we are not panicking.
			continue
		}
		if taskPastRetention(ti) {
			log.Info("an import task has passed retention period and will be removed from Etcd",
G
groot 已提交
930 931
				zap.Int64("task ID", ti.GetId()),
				zap.Int64("createTs", ti.GetCreateTs()),
932
				zap.Float64("ImportTaskRetention", Params.RootCoordCfg.ImportTaskRetention.GetAsFloat()))
933 934 935 936 937 938 939 940 941
			if err = m.yieldTaskInfo(ti.GetId()); err != nil {
				log.Error("failed to remove import task from Etcd",
					zap.Int64("task ID", ti.GetId()),
					zap.Error(err))
			}
		}
	}
}

942 943 944 945 946 947 948 949 950
// releaseHangingBusyDataNode checks if a busy DataNode has been 'busy' for an unexpected long time.
// We will then remove these DataNodes from `busy list`.
func (m *importManager) releaseHangingBusyDataNode() {
	m.busyNodesLock.Lock()
	for nodeID, ts := range m.busyNodes {
		log.Info("busy DataNode found",
			zap.Int64("node ID", nodeID),
			zap.Int64("busy duration (seconds)", time.Now().Unix()-ts),
		)
951
		if Params.RootCoordCfg.ImportTaskExpiration.GetAsFloat() <= float64(time.Now().Unix()-ts) {
952 953 954 955 956 957 958 959
			log.Warn("release a hanging busy DataNode",
				zap.Int64("node ID", nodeID))
			delete(m.busyNodes, nodeID)
		}
	}
	m.busyNodesLock.Unlock()
}

960 961 962 963 964 965
func rearrangeTasks(tasks []*milvuspb.GetImportStateResponse) {
	sort.Slice(tasks, func(i, j int) bool {
		return tasks[i].GetId() < tasks[j].GetId()
	})
}

G
groot 已提交
966
func (m *importManager) listAllTasks(colID int64, limit int64) ([]*milvuspb.GetImportStateResponse, error) {
967 968 969 970
	var importTasks []*datapb.ImportTaskInfo
	var err error
	if importTasks, err = m.loadFromTaskStore(false); err != nil {
		log.Error("failed to load from task store", zap.Error(err))
G
groot 已提交
971
		return nil, fmt.Errorf("failed to load task list from etcd, error: %w", err)
972
	}
973

G
groot 已提交
974 975 976
	tasks := make([]*milvuspb.GetImportStateResponse, 0)
	// filter tasks by collection id
	// if colID is negative, we will return all tasks
977
	for _, task := range importTasks {
G
groot 已提交
978 979 980 981
		if colID < 0 || colID == task.GetCollectionId() {
			currTask := &milvuspb.GetImportStateResponse{}
			m.copyTaskInfo(task, currTask)
			tasks = append(tasks, currTask)
G
groot 已提交
982
		}
983
	}
G
groot 已提交
984

G
groot 已提交
985
	// arrange tasks by id in ascending order, actually, id is the create time of a task
986
	rearrangeTasks(tasks)
987 988 989

	// if limit is 0 or larger than length of tasks, return all tasks
	if limit <= 0 || limit >= int64(len(tasks)) {
G
groot 已提交
990
		return tasks, nil
991 992 993
	}

	// return the newly tasks from the tail
G
groot 已提交
994
	return tasks[len(tasks)-int(limit):], nil
G
groot 已提交
995 996
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
// removeBadImportSegments marks segments of a failed import task as `dropped`.
func (m *importManager) removeBadImportSegments(ctx context.Context) {
	var taskList []*datapb.ImportTaskInfo
	var err error
	if taskList, err = m.loadFromTaskStore(false); err != nil {
		log.Error("failed to load from task store",
			zap.Error(err))
		return
	}
	for _, t := range taskList {
		// Only check newly failed tasks.
		if t.GetState().GetStateCode() != commonpb.ImportState_ImportFailed {
			continue
		}
		log.Info("trying to mark segments as dropped",
			zap.Int64("task ID", t.GetId()),
			zap.Int64s("segment IDs", t.GetState().GetSegments()))
1014

1015
		if err = m.setImportTaskState(t.GetId(), commonpb.ImportState_ImportFailedAndCleaned); err != nil {
1016
			log.Warn("failed to set ", zap.Int64("task ID", t.GetId()), zap.Error(err))
1017 1018 1019 1020
		}
	}
}

1021 1022
// BuildImportTaskKey constructs and returns an Etcd key with given task ID.
func BuildImportTaskKey(taskID int64) string {
1023
	return fmt.Sprintf("%s%s%d", Params.RootCoordCfg.ImportTaskSubPath.GetValue(), delimiter, taskID)
1024
}
1025

1026
// taskExpired returns true if the in-mem task is considered expired.
1027
func taskExpired(ti *datapb.ImportTaskInfo) bool {
1028
	return Params.RootCoordCfg.ImportTaskExpiration.GetAsFloat() <= float64(time.Now().Unix()-ti.GetStartTs())
1029 1030 1031 1032
}

// taskPastRetention returns true if the task is considered expired in Etcd.
func taskPastRetention(ti *datapb.ImportTaskInfo) bool {
1033
	return Params.RootCoordCfg.ImportTaskRetention.GetAsFloat() <= float64(time.Now().Unix()-ti.GetCreateTs())
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
}

func tryUpdateErrMsg(errReason string, toPersistImportTaskInfo *datapb.ImportTaskInfo) {
	if errReason != "" {
		if toPersistImportTaskInfo.GetState().GetErrorMessage() == "" {
			toPersistImportTaskInfo.State.ErrorMessage = errReason
		} else {
			toPersistImportTaskInfo.State.ErrorMessage =
				fmt.Sprintf("%s; %s",
					toPersistImportTaskInfo.GetState().GetErrorMessage(),
					errReason)
		}
	}
}

func cloneImportTaskInfo(taskInfo *datapb.ImportTaskInfo) *datapb.ImportTaskInfo {
	cloned := &datapb.ImportTaskInfo{
		Id:             taskInfo.GetId(),
		DatanodeId:     taskInfo.GetDatanodeId(),
		CollectionId:   taskInfo.GetCollectionId(),
		PartitionId:    taskInfo.GetPartitionId(),
		ChannelNames:   taskInfo.GetChannelNames(),
		Files:          taskInfo.GetFiles(),
		CreateTs:       taskInfo.GetCreateTs(),
		State:          taskInfo.GetState(),
		CollectionName: taskInfo.GetCollectionName(),
		PartitionName:  taskInfo.GetPartitionName(),
1061
		Infos:          taskInfo.GetInfos(),
G
groot 已提交
1062
		StartTs:        taskInfo.GetStartTs(),
1063 1064
	}
	return cloned
1065
}