historical.go 8.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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.

package querynode

import (
	"context"
16 17
	"errors"
	"fmt"
18 19 20
	"path/filepath"
	"strconv"
	"sync"
21

22
	"github.com/golang/protobuf/proto"
23
	etcdkv "github.com/milvus-io/milvus/internal/kv/etcd"
24
	"go.etcd.io/etcd/api/v3/mvccpb"
25 26 27
	"go.uber.org/zap"

	"github.com/milvus-io/milvus/internal/log"
28
	"github.com/milvus-io/milvus/internal/msgstream"
29
	"github.com/milvus-io/milvus/internal/proto/querypb"
30 31
	"github.com/milvus-io/milvus/internal/proto/segcorepb"
	"github.com/milvus-io/milvus/internal/storage"
32 33 34
	"github.com/milvus-io/milvus/internal/types"
)

35 36 37 38
const (
	segmentMetaPrefix = "queryCoord-segmentMeta"
)

39
// historical is in charge of historical data in query node
40
type historical struct {
41 42
	ctx context.Context

43
	replica      ReplicaInterface
44
	loader       *segmentLoader
45
	statsService *statsService
46

47 48 49 50
	mu                   sync.Mutex // guards globalSealedSegments
	globalSealedSegments map[UniqueID]*querypb.SegmentInfo

	etcdKV *etcdkv.EtcdKV
51 52 53
}

func newHistorical(ctx context.Context,
54 55
	rootCoord types.RootCoord,
	indexCoord types.IndexCoord,
56 57 58
	factory msgstream.Factory,
	etcdKV *etcdkv.EtcdKV) *historical {
	replica := newCollectionReplica(etcdKV)
59
	loader := newSegmentLoader(ctx, rootCoord, indexCoord, replica, etcdKV)
60
	ss := newStatsService(ctx, replica, loader.indexLoader.fieldStatsChan, factory)
61 62

	return &historical{
63 64 65 66 67 68
		ctx:                  ctx,
		replica:              replica,
		loader:               loader,
		statsService:         ss,
		globalSealedSegments: make(map[UniqueID]*querypb.SegmentInfo),
		etcdKV:               etcdKV,
69 70 71 72
	}
}

func (h *historical) start() {
73 74
	go h.statsService.start()
	go h.watchGlobalSegmentMeta()
75 76 77 78 79 80 81 82
}

func (h *historical) close() {
	h.statsService.close()

	// free collectionReplica
	h.replica.freeAll()
}
83

84 85 86 87 88 89 90 91 92 93 94 95 96
func (h *historical) watchGlobalSegmentMeta() {
	log.Debug("query node watchGlobalSegmentMeta start")
	watchChan := h.etcdKV.WatchWithPrefix(segmentMetaPrefix)

	for {
		select {
		case <-h.ctx.Done():
			log.Debug("query node watchGlobalSegmentMeta close")
			return
		case resp := <-watchChan:
			for _, event := range resp.Events {
				segmentID, err := strconv.ParseInt(filepath.Base(string(event.Kv.Key)), 10, 64)
				if err != nil {
B
bigsheeper 已提交
97
					log.Warn("watchGlobalSegmentMeta failed", zap.Any("error", err.Error()))
98 99 100 101 102 103 104 105
					continue
				}
				switch event.Type {
				case mvccpb.PUT:
					log.Debug("globalSealedSegments add segment",
						zap.Any("segmentID", segmentID),
					)
					segmentInfo := &querypb.SegmentInfo{}
106
					err = proto.Unmarshal(event.Kv.Value, segmentInfo)
107
					if err != nil {
B
bigsheeper 已提交
108
						log.Warn("watchGlobalSegmentMeta failed", zap.Any("error", err.Error()))
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 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 182
						continue
					}
					h.addGlobalSegmentInfo(segmentID, segmentInfo)
				case mvccpb.DELETE:
					log.Debug("globalSealedSegments delete segment",
						zap.Any("segmentID", segmentID),
					)
					h.removeGlobalSegmentInfo(segmentID)
				}
			}
		}
	}
}

func (h *historical) addGlobalSegmentInfo(segmentID UniqueID, segmentInfo *querypb.SegmentInfo) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.globalSealedSegments[segmentID] = segmentInfo
}

func (h *historical) removeGlobalSegmentInfo(segmentID UniqueID) {
	h.mu.Lock()
	defer h.mu.Unlock()
	delete(h.globalSealedSegments, segmentID)
}

func (h *historical) getGlobalSegmentIDsByCollectionID(collectionID UniqueID) []UniqueID {
	h.mu.Lock()
	defer h.mu.Unlock()
	resIDs := make([]UniqueID, 0)
	for _, v := range h.globalSealedSegments {
		if v.CollectionID == collectionID {
			resIDs = append(resIDs, v.SegmentID)
		}
	}
	return resIDs
}

func (h *historical) getGlobalSegmentIDsByPartitionIds(partitionIDs []UniqueID) []UniqueID {
	h.mu.Lock()
	defer h.mu.Unlock()
	resIDs := make([]UniqueID, 0)
	for _, v := range h.globalSealedSegments {
		for _, partitionID := range partitionIDs {
			if v.PartitionID == partitionID {
				resIDs = append(resIDs, v.SegmentID)
			}
		}
	}
	return resIDs
}

func (h *historical) removeGlobalSegmentIDsByCollectionID(collectionID UniqueID) {
	h.mu.Lock()
	defer h.mu.Unlock()
	for _, v := range h.globalSealedSegments {
		if v.CollectionID == collectionID {
			delete(h.globalSealedSegments, v.SegmentID)
		}
	}
}

func (h *historical) removeGlobalSegmentIDsByPartitionIds(partitionIDs []UniqueID) {
	h.mu.Lock()
	defer h.mu.Unlock()
	for _, v := range h.globalSealedSegments {
		for _, partitionID := range partitionIDs {
			if v.PartitionID == partitionID {
				delete(h.globalSealedSegments, v.SegmentID)
			}
		}
	}
}

183
func (h *historical) retrieve(collID UniqueID, partIDs []UniqueID, vcm storage.ChunkManager,
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
	plan *RetrievePlan) ([]*segcorepb.RetrieveResults, []UniqueID, error) {

	retrieveResults := make([]*segcorepb.RetrieveResults, 0)
	retrieveSegmentIDs := make([]UniqueID, 0)

	// get historical partition ids
	var retrievePartIDs []UniqueID
	if len(partIDs) == 0 {
		hisPartIDs, err := h.replica.getPartitionIDs(collID)
		if err != nil {
			return retrieveResults, retrieveSegmentIDs, err
		}
		retrievePartIDs = hisPartIDs
	} else {
		for _, id := range partIDs {
			_, err := h.replica.getPartitionByID(id)
			if err == nil {
				retrievePartIDs = append(retrievePartIDs, id)
			}
		}
	}

	for _, partID := range retrievePartIDs {
		segIDs, err := h.replica.getSegmentIDs(partID)
		if err != nil {
			return retrieveResults, retrieveSegmentIDs, err
		}
		for _, segID := range segIDs {
			seg, err := h.replica.getSegmentByID(segID)
			if err != nil {
				return retrieveResults, retrieveSegmentIDs, err
			}
			result, err := seg.getEntityByIds(plan)
			if err != nil {
				return retrieveResults, retrieveSegmentIDs, err
			}

221
			if err = seg.fillVectorFieldsData(collID, vcm, result); err != nil {
222 223 224 225 226 227 228 229 230
				return retrieveResults, retrieveSegmentIDs, err
			}
			retrieveResults = append(retrieveResults, result)
			retrieveSegmentIDs = append(retrieveSegmentIDs, segID)
		}
	}
	return retrieveResults, retrieveSegmentIDs, nil
}

231
// search will search all the target segments in historical
232 233
func (h *historical) search(searchReqs []*searchRequest, collID UniqueID, partIDs []UniqueID, plan *SearchPlan,
	searchTs Timestamp) ([]*SearchResult, []UniqueID, error) {
234 235

	searchResults := make([]*SearchResult, 0)
236
	searchSegmentIDs := make([]UniqueID, 0)
237 238 239 240 241 242

	// get historical partition ids
	var searchPartIDs []UniqueID
	if len(partIDs) == 0 {
		hisPartIDs, err := h.replica.getPartitionIDs(collID)
		if err != nil {
243
			return searchResults, searchSegmentIDs, err
244
		}
245 246 247 248
		log.Debug("no partition specified, search all partitions",
			zap.Any("collectionID", collID),
			zap.Any("all partitions", hisPartIDs),
		)
249 250 251 252 253
		searchPartIDs = hisPartIDs
	} else {
		for _, id := range partIDs {
			_, err := h.replica.getPartitionByID(id)
			if err == nil {
254 255 256 257
				log.Debug("append search partition id",
					zap.Any("collectionID", collID),
					zap.Any("partitionID", id),
				)
258 259 260 261 262
				searchPartIDs = append(searchPartIDs, id)
			}
		}
	}

263 264 265 266 267
	col, err := h.replica.getCollectionByID(collID)
	if err != nil {
		return nil, nil, err
	}

268
	// all partitions have been released
269
	if len(searchPartIDs) == 0 && col.getLoadType() == loadTypePartition {
270
		return nil, nil, errors.New("partitions have been released , collectionID = " +
271
			fmt.Sprintln(collID) + "target partitionIDs = " + fmt.Sprintln(partIDs))
272 273
	}

274 275 276 277 278 279 280
	if len(searchPartIDs) == 0 && col.getLoadType() == loadTypeCollection {
		if err = col.checkReleasedPartitions(partIDs); err != nil {
			return nil, nil, err
		}
		return nil, nil, nil
	}

281 282 283 284 285 286
	log.Debug("doing search in historical",
		zap.Any("collectionID", collID),
		zap.Any("reqPartitionIDs", partIDs),
		zap.Any("searchPartitionIDs", searchPartIDs),
	)

287 288 289
	for _, partID := range searchPartIDs {
		segIDs, err := h.replica.getSegmentIDs(partID)
		if err != nil {
290
			return searchResults, searchSegmentIDs, err
291 292 293 294
		}
		for _, segID := range segIDs {
			seg, err := h.replica.getSegmentByID(segID)
			if err != nil {
295
				return searchResults, searchSegmentIDs, err
296 297 298 299
			}
			if !seg.getOnService() {
				continue
			}
300
			searchResult, err := seg.search(plan, searchReqs, []Timestamp{searchTs})
301
			if err != nil {
302
				return searchResults, searchSegmentIDs, err
303 304
			}
			searchResults = append(searchResults, searchResult)
305
			searchSegmentIDs = append(searchSegmentIDs, seg.segmentID)
306 307 308
		}
	}

309
	return searchResults, searchSegmentIDs, nil
310
}