util.go 6.7 KB
Newer Older
1 2 3 4 5 6
// 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
S
sunby 已提交
7 8
// with the License. You may obtain a copy of the License at
//
9
//     http://www.apache.org/licenses/LICENSE-2.0
S
sunby 已提交
10
//
11 12 13 14 15
// 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.
S
sunby 已提交
16

17
package datacoord
S
sunby 已提交
18 19

import (
20
	"context"
S
sunby 已提交
21
	"errors"
J
jaime 已提交
22
	"strconv"
23
	"sync"
24
	"time"
S
sunby 已提交
25

J
jaime 已提交
26 27
	"github.com/milvus-io/milvus/internal/common"

S
SimFG 已提交
28 29
	"github.com/milvus-io/milvus/api/commonpb"
	"github.com/milvus-io/milvus/api/schemapb"
30 31 32
	"github.com/milvus-io/milvus/internal/log"
	"github.com/milvus-io/milvus/internal/proto/indexpb"
	"github.com/milvus-io/milvus/internal/types"
S
sunby 已提交
33
	"github.com/milvus-io/milvus/internal/util/tsoutil"
34 35
	"github.com/milvus-io/milvus/internal/util/typeutil"
	"go.uber.org/zap"
S
sunby 已提交
36 37
)

C
congqixia 已提交
38
// Response response interface for verification
S
sunby 已提交
39 40 41 42
type Response interface {
	GetStatus() *commonpb.Status
}

C
congqixia 已提交
43
// VerifyResponse verify grpc Response 1. check error is nil 2. check response.GetStatus() with status success
S
sunby 已提交
44 45 46 47 48
func VerifyResponse(response interface{}, err error) error {
	if err != nil {
		return err
	}
	if response == nil {
S
sunby 已提交
49
		return errNilResponse
S
sunby 已提交
50 51 52
	}
	switch resp := response.(type) {
	case Response:
X
Xieql 已提交
53
		// note that resp will not be nil here, since it's still an interface
C
congqixia 已提交
54 55 56 57 58
		if resp.GetStatus() == nil {
			return errNilStatusResponse
		}
		if resp.GetStatus().GetErrorCode() != commonpb.ErrorCode_Success {
			return errors.New(resp.GetStatus().GetReason())
S
sunby 已提交
59 60
		}
	case *commonpb.Status:
C
congqixia 已提交
61 62 63
		if resp == nil {
			return errNilResponse
		}
64
		if resp.ErrorCode != commonpb.ErrorCode_Success {
C
congqixia 已提交
65
			return errors.New(resp.GetReason())
S
sunby 已提交
66 67
		}
	default:
S
sunby 已提交
68
		return errUnknownResponseType
S
sunby 已提交
69 70 71
	}
	return nil
}
72

73 74
// failResponse sets status to failed with unexpected error and reason.
func failResponse(status *commonpb.Status, reason string) {
75 76 77 78
	status.ErrorCode = commonpb.ErrorCode_UnexpectedError
	status.Reason = reason
}

79 80 81 82 83 84
// failResponseWithCode sets status to failed with error code and reason.
func failResponseWithCode(status *commonpb.Status, errCode commonpb.ErrorCode, reason string) {
	status.ErrorCode = errCode
	status.Reason = reason
}

85
func GetCompactTime(ctx context.Context, allocator allocator) (*compactTime, error) {
S
sunby 已提交
86 87 88 89 90 91
	ts, err := allocator.allocTimestamp(ctx)
	if err != nil {
		return nil, err
	}

	pts, _ := tsoutil.ParseTS(ts)
92 93 94 95 96 97 98
	ttRetention := pts.Add(-time.Duration(Params.CommonCfg.RetentionDuration) * time.Second)
	ttRetentionLogic := tsoutil.ComposeTS(ttRetention.UnixNano()/int64(time.Millisecond), 0)

	// TODO, change to collection level
	if Params.CommonCfg.EntityExpirationTTL > 0 {
		ttexpired := pts.Add(-Params.CommonCfg.EntityExpirationTTL)
		ttexpiredLogic := tsoutil.ComposeTS(ttexpired.UnixNano()/int64(time.Millisecond), 0)
J
jaime 已提交
99
		return &compactTime{ttRetentionLogic, ttexpiredLogic, Params.CommonCfg.EntityExpirationTTL}, nil
100 101
	}
	// no expiration time
J
jaime 已提交
102
	return &compactTime{ttRetentionLogic, 0, 0}, nil
S
sunby 已提交
103
}
104

105
func FilterInIndexedSegments(handler Handler, indexCoord types.IndexCoord, segments ...*SegmentInfo) []*SegmentInfo {
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	if len(segments) == 0 {
		return nil
	}

	segmentMap := make(map[int64]*SegmentInfo)
	collectionSegments := make(map[int64][]int64)
	// TODO(yah01): This can't handle the case of multiple vector fields exist,
	// modify it if we support multiple vector fields.
	vecFieldID := make(map[int64]int64)
	for _, segment := range segments {
		collectionID := segment.GetCollectionID()
		segmentMap[segment.GetID()] = segment
		collectionSegments[collectionID] = append(collectionSegments[collectionID], segment.GetID())
	}
	for collection := range collectionSegments {
121 122 123 124 125 126 127 128
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
		coll, err := handler.GetCollection(ctx, collection)
		cancel()
		if err != nil {
			log.Warn("failed to get collection schema", zap.Error(err))
			continue
		}
		for _, field := range coll.Schema.GetFields() {
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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
			if field.GetDataType() == schemapb.DataType_BinaryVector ||
				field.GetDataType() == schemapb.DataType_FloatVector {
				vecFieldID[collection] = field.GetFieldID()
				break
			}
		}
	}

	wg := sync.WaitGroup{}
	indexedSegmentCh := make(chan []int64, len(segments))
	for _, segment := range segments {
		segment := segment
		wg.Add(1)
		go func() {
			defer wg.Done()
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			resp, err := indexCoord.GetIndexInfos(ctx, &indexpb.GetIndexInfoRequest{
				CollectionID: segment.GetCollectionID(),
				SegmentIDs:   []int64{segment.GetID()},
			})
			if err != nil || resp.GetStatus().GetErrorCode() != commonpb.ErrorCode_Success {
				log.Warn("failed to get index of collection",
					zap.Int64("collectionID", segment.GetCollectionID()),
					zap.Int64("segmentID", segment.GetID()))
				return
			}
			indexed := extractSegmentsWithVectorIndex(vecFieldID, resp.GetSegmentInfo())
			if len(indexed) == 0 {
				log.Debug("no vector index for the segment",
					zap.Int64("collectionID", segment.GetCollectionID()),
					zap.Int64("segmentID", segment.GetID()))
				return
			}
			indexedSegmentCh <- indexed
		}()
	}
	wg.Wait()
	close(indexedSegmentCh)

	indexedSegments := make([]*SegmentInfo, 0)
	for segments := range indexedSegmentCh {
		for _, segment := range segments {
			if info, ok := segmentMap[segment]; ok {
				delete(segmentMap, segment)
				indexedSegments = append(indexedSegments, info)
			}
		}
	}

	return indexedSegments
}

func extractSegmentsWithVectorIndex(vecFieldID map[int64]int64, segentIndexInfo map[int64]*indexpb.SegmentInfo) []int64 {
	indexedSegments := make(typeutil.UniqueSet)
	for _, indexInfo := range segentIndexInfo {
		if !indexInfo.GetEnableIndex() {
			continue
		}
		for _, index := range indexInfo.GetIndexInfos() {
			if index.GetFieldID() == vecFieldID[indexInfo.GetCollectionID()] {
				indexedSegments.Insert(indexInfo.GetSegmentID())
				break
			}
		}
	}
	return indexedSegments.Collect()
}

198 199 200 201
func getZeroTime() time.Time {
	var t time.Time
	return t
}
J
jaime 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215

// getCollectionTTL returns ttl if collection's ttl is specified, or return global ttl
func getCollectionTTL(properties map[string]string) (time.Duration, error) {
	v, ok := properties[common.CollectionTTLConfigKey]
	if ok {
		ttl, err := strconv.Atoi(v)
		if err != nil {
			return -1, err
		}
		return time.Duration(ttl) * time.Second, nil
	}

	return Params.CommonCfg.EntityExpirationTTL, nil
}