query_req.go 5.9 KB
Newer Older
1
package proxy
S
shengjh 已提交
2 3

import (
Z
zhenshan.cao 已提交
4 5 6
	"log"
	"sync"

S
shengjh 已提交
7 8
	"github.com/apache/pulsar-client-go/pulsar"
	"github.com/golang/protobuf/proto"
9 10 11
	"github.com/zilliztech/milvus-distributed/internal/proto/commonpb"
	"github.com/zilliztech/milvus-distributed/internal/proto/internalpb"
	"github.com/zilliztech/milvus-distributed/internal/proto/servicepb"
S
shengjh 已提交
12 13 14
)

type queryReq struct {
15 16
	internalpb.SearchRequest
	result []*internalpb.SearchResult
S
shengjh 已提交
17 18 19 20 21
	wg     sync.WaitGroup
	proxy  *proxyServer
}

// BaseRequest interfaces
22 23
func (req *queryReq) Type() internalpb.MsgType {
	return req.MsgType
S
shengjh 已提交
24 25
}

26 27
func (req *queryReq) PreExecute() commonpb.Status {
	return commonpb.Status{ErrorCode: commonpb.ErrorCode_SUCCESS}
S
shengjh 已提交
28 29
}

30
func (req *queryReq) Execute() commonpb.Status {
S
shengjh 已提交
31
	req.proxy.reqSch.queryChan <- req
32
	return commonpb.Status{ErrorCode: commonpb.ErrorCode_SUCCESS}
S
shengjh 已提交
33 34
}

35
func (req *queryReq) PostExecute() commonpb.Status { // send into pulsar
S
shengjh 已提交
36
	req.wg.Add(1)
37
	return commonpb.Status{ErrorCode: commonpb.ErrorCode_SUCCESS}
S
shengjh 已提交
38 39
}

40
func (req *queryReq) WaitToFinish() commonpb.Status { // wait unitl send into pulsar
S
shengjh 已提交
41
	req.wg.Wait()
42
	return commonpb.Status{ErrorCode: commonpb.ErrorCode_SUCCESS}
S
shengjh 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
}

func (s *proxyServer) restartQueryRoutine(buf_size int) error {
	s.reqSch.queryChan = make(chan *queryReq, buf_size)
	pulsarClient, err := pulsar.NewClient(pulsar.ClientOptions{URL: s.pulsarAddr})
	if err != nil {
		return nil
	}
	query, err := pulsarClient.CreateProducer(pulsar.ProducerOptions{Topic: s.queryTopic})
	if err != nil {
		return err
	}

	result, err := pulsarClient.Subscribe(pulsar.ConsumerOptions{
		Topic:                       s.resultTopic,
		SubscriptionName:            s.resultGroup,
		Type:                        pulsar.KeyShared,
		SubscriptionInitialPosition: pulsar.SubscriptionPositionEarliest,
	})
	if err != nil {
		return err
	}

Z
zhenshan.cao 已提交
66
	resultMap := make(map[int64]*queryReq)
S
shengjh 已提交
67 68 69 70 71 72 73 74 75 76

	go func() {
		defer result.Close()
		defer query.Close()
		defer pulsarClient.Close()
		for {
			select {
			case <-s.ctx.Done():
				return
			case qm := <-s.reqSch.queryChan:
Z
zhenshan.cao 已提交
77 78 79
				ts, err := s.getTimestamp(1)
				if err != nil {
					log.Printf("get time stamp failed")
S
shengjh 已提交
80 81
					break
				}
82
				qm.Timestamp = uint64(ts[0])
S
shengjh 已提交
83

84
				qb, err := proto.Marshal(qm)
S
shengjh 已提交
85 86 87 88 89 90 91
				if err != nil {
					log.Printf("Marshal QueryReqMsg failed, error = %v", err)
					continue
				}
				if _, err := query.Send(s.ctx, &pulsar.ProducerMessage{Payload: qb}); err != nil {
					log.Printf("post into puslar failed, error = %v", err)
				}
92 93 94
				s.reqSch.qTimestampMux.Lock()
				if s.reqSch.qTimestamp <= ts[0] {
					s.reqSch.qTimestamp = ts[0]
S
shengjh 已提交
95
				} else {
96
					log.Printf("there is some wrong with q_timestamp, it goes back, current = %d, previous = %d", ts[0], s.reqSch.qTimestamp)
S
shengjh 已提交
97
				}
98
				s.reqSch.qTimestampMux.Unlock()
99
				resultMap[qm.ReqId] = qm
S
shengjh 已提交
100 101 102 103 104 105
				//log.Printf("start search, query id = %d", qm.QueryId)
			case cm, ok := <-result.Chan():
				if !ok {
					log.Printf("consumer of result topic has closed")
					return
				}
106
				var rm internalpb.SearchResult
S
shengjh 已提交
107 108 109 110 111 112 113
				if err := proto.Unmarshal(cm.Message.Payload(), &rm); err != nil {
					log.Printf("Unmarshal QueryReqMsg failed, error = %v", err)
					break
				}
				if rm.ProxyId != s.proxyId {
					break
				}
114
				qm, ok := resultMap[rm.ReqId]
S
shengjh 已提交
115
				if !ok {
116
					log.Printf("unknown query id = %d", rm.ReqId)
S
shengjh 已提交
117 118 119 120 121
					break
				}
				qm.result = append(qm.result, &rm)
				if len(qm.result) == s.numReaderNode {
					qm.wg.Done()
122
					delete(resultMap, rm.ReqId)
S
shengjh 已提交
123 124 125 126 127 128 129 130 131
				}
				result.AckID(cm.ID())
			}

		}
	}()
	return nil
}

132 133 134 135 136 137 138 139
//func (s *proxyServer) reduceResult(query *queryReq) *servicepb.QueryResult {
//}

func (s *proxyServer) reduceResults(query *queryReq) *servicepb.QueryResult {

	var results []*internalpb.SearchResult
	var status commonpb.Status
	status.ErrorCode = commonpb.ErrorCode_UNEXPECTED_ERROR
S
shengjh 已提交
140
	for _, r := range query.result {
141 142 143
		status = *r.Status
		if status.ErrorCode == commonpb.ErrorCode_SUCCESS {
			results = append(results, r)
Z
zhenshan.cao 已提交
144
		} else {
145
			break
S
shengjh 已提交
146 147
		}
	}
Z
zhenshan.cao 已提交
148
	if len(results) != s.numReaderNode {
149
		status.ErrorCode = commonpb.ErrorCode_UNEXPECTED_ERROR
S
shengjh 已提交
150
	}
Z
zhenshan.cao 已提交
151 152
	if status.ErrorCode != commonpb.ErrorCode_SUCCESS {
		result := servicepb.QueryResult{
153
			Status: &status,
S
shengjh 已提交
154
		}
155
		return &result
S
shengjh 已提交
156 157
	}

158
	if s.numReaderNode == 1 {
Z
zhenshan.cao 已提交
159
		result := servicepb.QueryResult{
160 161 162 163
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_SUCCESS,
			},
			Hits: results[0].Hits,
S
shengjh 已提交
164
		}
165
		return &result
S
shengjh 已提交
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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
	//var entities []*struct {
	//	Idx       int64
	//	Score 	  float32
	//	Hit		  *servicepb.Hits
	//}
	//var rows int
	//
	//result_err := func(msg string) *pb.QueryResult {
	//	return &pb.QueryResult{
	//		Status: &pb.Status{
	//			ErrorCode: pb.ErrorCode_UNEXPECTED_ERROR,
	//			Reason:    msg,
	//		},
	//	}
	//}

	//for _, r := range results {
	//	for i := 0; i < len(r.Hits); i++ {
	//		entity := struct {
	//			Ids       int64
	//			ValidRow  bool
	//			RowsData  *pb.RowData
	//			Scores    float32
	//			Distances float32
	//		}{
	//			Ids:       r.Entities.Ids[i],
	//			ValidRow:  r.Entities.ValidRow[i],
	//			RowsData:  r.Entities.RowsData[i],
	//			Scores:    r.Scores[i],
	//			Distances: r.Distances[i],
	//		}
	//		entities = append(entities, &entity)
	//	}
	//}
	//sort.Slice(entities, func(i, j int) bool {
	//	if entities[i].ValidRow == true {
	//		if entities[j].ValidRow == false {
	//			return true
	//		}
	//		return entities[i].Scores > entities[j].Scores
	//	} else {
	//		return false
	//	}
	//})
	//rIds := make([]int64, 0, rows)
	//rValidRow := make([]bool, 0, rows)
	//rRowsData := make([]*pb.RowData, 0, rows)
	//rScores := make([]float32, 0, rows)
	//rDistances := make([]float32, 0, rows)
	//for i := 0; i < rows; i++ {
	//	rIds = append(rIds, entities[i].Ids)
	//	rValidRow = append(rValidRow, entities[i].ValidRow)
	//	rRowsData = append(rRowsData, entities[i].RowsData)
	//	rScores = append(rScores, entities[i].Scores)
	//	rDistances = append(rDistances, entities[i].Distances)
	//}

	return &servicepb.QueryResult{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
S
shengjh 已提交
228 229 230
		},
	}
}