-
Notifications
You must be signed in to change notification settings - Fork 17
/
sparse.go
416 lines (369 loc) · 10.5 KB
/
sparse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2020 Zhizhesihai (Beijing) Technology Limited.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package tables
import (
"bytes"
"context"
"sync"
"time"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/util/logutil"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
tspb "github.com/zhihu/zetta-proto/pkg/tablestore"
"github.com/zhihu/zetta/pkg/metrics"
"github.com/zhihu/zetta/pkg/model"
"github.com/zhihu/zetta/pkg/tablecodec"
"github.com/zhihu/zetta/tablestore/sessionctx"
"github.com/zhihu/zetta/tablestore/table"
)
var (
fetchSparseCounterOK = metrics.FetchSparseCounter.WithLabelValues(metrics.LblOK)
fetchSparseCounterErr = metrics.FetchSparseCounter.WithLabelValues(metrics.LblError)
fetchSparseDurationOK = metrics.FetchSparseDuration.WithLabelValues(metrics.LblOK)
fetchSparseDurationErr = metrics.FetchSparseDuration.WithLabelValues(metrics.LblError)
batchSparseCounterOK = metrics.BatchSparseCounter.WithLabelValues(metrics.LblOK)
batchSparseCounterErr = metrics.BatchSparseCounter.WithLabelValues(metrics.LblError)
batchSparseDurationOK = metrics.BatchSparseDuration.WithLabelValues(metrics.LblOK)
scanSparseCounterOK = metrics.ScanSparseCounter.WithLabelValues(metrics.LblOK)
scanSparseCounterErr = metrics.ScanSparseCounter.WithLabelValues(metrics.LblError)
scanSparseDurationOK = metrics.ScanSparseDuration.WithLabelValues(metrics.LblOK)
)
const streamingBatchSize = 1000
type sparseRow struct {
idx int
raw *tspb.Row
entireRow bool
rowCells *tspb.SliceCell
rkeyPrefix kv.Key
}
type sparseContext struct {
cf *model.ColumnFamilyMeta
rowKeys []kv.Key
cellMap map[string]*sparseRow
srows []*sparseRow
}
func buildSparseContext(cf *model.ColumnFamilyMeta) *sparseContext {
return &sparseContext{
cf: cf,
rowKeys: []kv.Key{},
cellMap: map[string]*sparseRow{},
srows: []*sparseRow{},
}
}
func (t *tableCommon) ReadSparse(ctx context.Context, req *tspb.SparseReadRequest) (*resultIter, error) {
if req.Family == DefaultColumnFamily {
return nil, status.Error(codes.FailedPrecondition, "default column family not suitable for sparse read")
}
sparseCtxs, _, err := t.prepareRowKeys(ctx, req)
if err != nil {
return nil, err
}
ri := NewResultIter(req.Limit)
go func() {
defer ri.Close()
for _, sparseCtx := range sparseCtxs {
startTS := time.Now()
err := t.fetchSparse(ctx, sparseCtx, ri)
durFetchSparse := time.Since(startTS)
if err != nil {
fetchSparseCounterErr.Inc()
fetchSparseDurationErr.Observe(durFetchSparse.Seconds())
ri.lastErr = err
logutil.Logger(ctx).Error("fetch sparse value err", zap.Error(err))
return
}
fetchSparseDurationOK.Observe(durFetchSparse.Seconds())
fetchSparseCounterOK.Inc()
}
}()
return ri, nil
}
func (t *tableCommon) prepareRowKeys(ctx context.Context, sr *tspb.SparseReadRequest) ([]*sparseContext, []*model.ColumnFamilyMeta, error) {
var (
sparseCtxs = []*sparseContext{}
cfList = []*model.ColumnFamilyMeta{}
)
if sr.Family == "" {
for _, cf := range t.cfIDMap {
if isFlexible(cf) {
cfList = append(cfList, cf)
sparseCtx := buildSparseContext(cf)
sparseCtxs = append(sparseCtxs, sparseCtx)
}
}
} else {
cf, ok := t.cfIDMap[sr.Family]
if !ok {
return nil, nil, status.Errorf(codes.NotFound, "column family: %v not found", sr.Family)
}
if !isFlexible(cf) {
return nil, nil, status.Errorf(codes.Canceled, "columns famliy %v mode not flexible", sr.Family)
}
cfList = append(cfList, cf)
sparseCtx := buildSparseContext(cf)
sparseCtxs = append(sparseCtxs, sparseCtx)
}
for scid, cf := range cfList {
for i, row := range sr.Rows {
pkeyDatums, err := t.getPrimaryKeyData(ctx, row.Keys)
if err != nil {
return nil, nil, status.Error(codes.Aborted, err.Error())
}
rkeyPrefix, err := genRecordPrimaryCFPrefix(t.tableID, pkeyDatums, cf.Id)
if err != nil {
return nil, nil, status.Error(codes.Aborted, err.Error())
}
srow := &sparseRow{
idx: i,
raw: row,
rkeyPrefix: rkeyPrefix,
rowCells: &tspb.SliceCell{
PrimaryKeys: row.Keys.Values,
Cells: []*tspb.Cell{},
},
}
sparseCtxs[scid].srows = append(sparseCtxs[scid].srows, srow)
if len(row.Qualifiers) == 0 {
srow.entireRow = true
continue
}
for _, col := range row.Qualifiers {
rkey := tablecodec.EncodePkCFColumn(rkeyPrefix, []byte(col))
sparseCtxs[scid].rowKeys = append(sparseCtxs[scid].rowKeys, rkey)
sparseCtxs[scid].cellMap[string(rkey)] = srow
}
}
}
return sparseCtxs, cfList, nil
}
func (t *tableCommon) fetchSparse(ctx context.Context, sparseCtx *sparseContext, ri *resultIter) error {
var (
wg sync.WaitGroup
err1, err2 error
rowKeys = sparseCtx.rowKeys
cellMap = sparseCtx.cellMap
srows = sparseCtx.srows
cf = sparseCtx.cf
)
streamRead := sessionctx.StreamReadFromContext(ctx)
startTs := time.Now()
if len(rowKeys) > 0 {
if !streamRead {
wg.Add(1)
}
go func() {
if !streamRead {
defer wg.Done()
}
err1 = t.readSparseBatch(ctx, rowKeys, cellMap, cf, ri)
if err1 != nil {
batchSparseCounterErr.Inc()
return
}
batchSparseCounterOK.Inc()
batchSparseDurationOK.Observe(time.Since(startTs).Seconds())
}()
}
err2 = t.scanSparseRow(ctx, srows, cf, ri)
if err2 != nil {
scanSparseCounterErr.Inc()
return err2
}
scanSparseCounterOK.Inc()
scanSparseDurationOK.Observe(time.Since(startTs).Seconds())
if !streamRead {
wg.Wait()
}
if err1 != nil {
return err1
}
if !streamRead {
for _, srow := range srows {
ri.sendData(srow.rowCells)
}
}
return nil
}
func (t *tableCommon) readSparseBatch(ctx context.Context, rowKeys []kv.Key, cellMap map[string]*sparseRow, cf *model.ColumnFamilyMeta, ri *resultIter) error {
var (
txn = ctx.Value(sessionctx.TxnIDKey).(kv.Transaction)
sc = &stmtctx.StatementContext{TimeZone: time.Local}
streamRead = sessionctx.StreamReadFromContext(ctx)
preIdx = -1
preSrow *sparseRow = nil
)
valsMap, err := txn.BatchGet(ctx, rowKeys)
if err != nil {
logutil.Logger(ctx).Error("batch get row value error", zap.Error(err))
return err
}
for i := 0; i < len(rowKeys); i++ {
val, ok := valsMap[string(rowKeys[i])]
if !ok {
continue
}
srow := cellMap[string(rowKeys[i])]
if srow.idx > preIdx {
if preSrow != nil && streamRead {
if err := ri.sendData(preSrow.rowCells); err == table.ErrResultSetUserLimitReached {
return nil
}
}
preIdx = srow.idx
preSrow = srow
if srow.rowCells == nil {
srow.rowCells = &tspb.SliceCell{
PrimaryKeys: srow.raw.Keys.Values,
Cells: []*tspb.Cell{},
}
}
}
datum, err := tablecodec.DecodeRowHigh(sc, val, nil, time.Local)
if err != nil {
return err
}
pv, _, err := flexibleProtoValueFromDatum(datum)
if err != nil {
logutil.Logger(ctx).Error("gen proto value error", zap.Error(err))
return err
}
column := rowKeys[i][len(srow.rkeyPrefix):]
cell := &tspb.Cell{
Family: cf.Name,
Column: string(column),
Type: &tspb.Type{Code: tspb.TypeCode_TYPE_CODE_UNSPECIFIED},
Value: pv,
}
srow.rowCells.Cells = append(srow.rowCells.Cells, cell)
}
return nil
}
type kvPair struct {
key []byte
value []byte
sRow *sparseRow
err error
}
func (t *tableCommon) scanSparseRow(ctx context.Context, srows []*sparseRow, cf *model.ColumnFamilyMeta, ri *resultIter) error {
if len(srows) == 0 {
return nil
}
var (
txn = ctx.Value(sessionctx.TxnIDKey).(kv.Transaction)
sc = &stmtctx.StatementContext{TimeZone: time.Local}
streamRead = sessionctx.StreamReadFromContext(ctx)
streamBatchIndex = 0
)
var cells []*tspb.Cell
kvPairChan := make(chan *kvPair, 10000)
defer close(kvPairChan)
go func() {
for _, srow := range srows {
if !srow.entireRow {
continue
}
iter, err := txn.Iter(srow.rkeyPrefix, srow.rkeyPrefix.PrefixNext())
if err != nil {
logutil.Logger(ctx).Error("get iterator error", zap.Error(err))
pair := &kvPair{
err: err,
}
kvPairChan <- pair
return
}
defer iter.Close()
for iter.Valid() {
if ctxErr := ctx.Err(); ctxErr != nil {
logutil.Logger(ctx).Error("Client canceled scan", zap.Error(ctxErr))
pair := &kvPair{
err: ctxErr,
}
kvPairChan <- pair
return
}
pair := &kvPair{
key: iter.Key(),
value: iter.Value(),
sRow: srow,
}
kvPairChan <- pair
iter.Next()
}
}
kvPairChan <- nil
}()
srow := srows[0]
for pair := range kvPairChan {
if pair != nil && pair.err != nil {
return pair.err
}
if pair == nil || pair.sRow != srow {
if streamBatchIndex > 0 {
rowCells := &tspb.SliceCell{
PrimaryKeys: srow.rowCells.PrimaryKeys,
Cells: cells[:streamBatchIndex],
}
if err := ri.sendData(rowCells); err != nil {
return err
}
streamBatchIndex = 0
}
if pair == nil {
return nil
}
srow = pair.sRow
}
datum, err := tablecodec.DecodeRowHigh(sc, pair.value, nil, time.Local)
if err != nil {
return err
}
pv, _, err := flexibleProtoValueFromDatum(datum)
if err != nil {
logutil.Logger(ctx).Error("gen proto value error", zap.Error(err))
return err
}
column := pair.key[len(srow.rkeyPrefix):]
cell := &tspb.Cell{
Family: cf.Name,
Column: string(column),
Type: &tspb.Type{Code: tspb.TypeCode_TYPE_CODE_UNSPECIFIED},
Value: pv,
}
if streamRead {
if streamBatchIndex == 0 {
cells = make([]*tspb.Cell, streamingBatchSize)
}
cells[streamBatchIndex] = cell
streamBatchIndex++
if streamBatchIndex >= streamingBatchSize {
streamBatchIndex = 0
rowCells := &tspb.SliceCell{
PrimaryKeys: srow.rowCells.PrimaryKeys,
Cells: cells,
}
if err := ri.sendData(rowCells); err != nil {
return err
}
}
} else {
srow.rowCells.Cells = append(srow.rowCells.Cells, cell)
}
}
return nil
}
func hasSuffix(rkey kv.Key, column []byte) bool {
return bytes.HasSuffix(rkey, column)
}