|
| 1 | +package aws |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/base64" |
| 6 | + "fmt" |
| 7 | + "strings" |
| 8 | + "sync" |
| 9 | + |
| 10 | + "github.com/aws/aws-sdk-go/aws" |
| 11 | + "github.com/aws/aws-sdk-go/aws/client" |
| 12 | + "github.com/aws/aws-sdk-go/aws/request" |
| 13 | + "github.com/aws/aws-sdk-go/service/dynamodb" |
| 14 | + gklog "github.com/go-kit/kit/log" |
| 15 | + "github.com/go-kit/kit/log/level" |
| 16 | + "github.com/pkg/errors" |
| 17 | + "github.com/prometheus/client_golang/prometheus" |
| 18 | + "golang.org/x/sync/errgroup" |
| 19 | + |
| 20 | + "github.com/cortexproject/cortex/pkg/chunk" |
| 21 | +) |
| 22 | + |
| 23 | +type dynamodbIndexReader struct { |
| 24 | + dynamoDBStorageClient |
| 25 | + |
| 26 | + log gklog.Logger |
| 27 | + maxRetries int |
| 28 | + |
| 29 | + rowsRead prometheus.Counter |
| 30 | +} |
| 31 | + |
| 32 | +// NewDynamoDBIndexReader returns an object that can scan an entire index table |
| 33 | +func NewDynamoDBIndexReader(cfg DynamoDBConfig, schemaCfg chunk.SchemaConfig, reg prometheus.Registerer, l gklog.Logger, rowsRead prometheus.Counter) (chunk.IndexReader, error) { |
| 34 | + client, err := newDynamoDBStorageClient(cfg, schemaCfg, reg) |
| 35 | + if err != nil { |
| 36 | + return nil, err |
| 37 | + } |
| 38 | + |
| 39 | + return &dynamodbIndexReader{ |
| 40 | + dynamoDBStorageClient: *client, |
| 41 | + maxRetries: cfg.BackoffConfig.MaxRetries, |
| 42 | + log: l, |
| 43 | + |
| 44 | + rowsRead: rowsRead, |
| 45 | + }, nil |
| 46 | +} |
| 47 | + |
| 48 | +func (r *dynamodbIndexReader) IndexTableNames(ctx context.Context) ([]string, error) { |
| 49 | + // fake up a table client - if we call NewDynamoDBTableClient() it will double-register metrics |
| 50 | + tableClient := dynamoTableClient{ |
| 51 | + DynamoDB: r.DynamoDB, |
| 52 | + metrics: r.metrics, |
| 53 | + } |
| 54 | + return tableClient.ListTables(ctx) |
| 55 | +} |
| 56 | + |
| 57 | +type seriesMap struct { |
| 58 | + mutex sync.Mutex // protect concurrent access to maps |
| 59 | + seriesProcessed map[string]sha256Set // map of userID/bucket to set showing which series have been processed |
| 60 | +} |
| 61 | + |
| 62 | +// Since all sha256 values are the same size, a fixed-size array |
| 63 | +// is more space-efficient than string or byte slice |
| 64 | +type sha256 [32]byte |
| 65 | + |
| 66 | +// an entry in this set indicates we have processed a series with that sha already |
| 67 | +type sha256Set struct { |
| 68 | + series map[sha256]struct{} |
| 69 | +} |
| 70 | + |
| 71 | +// ReadIndexEntries reads the whole of a table on multiple goroutines in parallel. |
| 72 | +// Entries for the same HashValue and RangeValue should be passed to the same processor. |
| 73 | +func (r *dynamodbIndexReader) ReadIndexEntries(ctx context.Context, tableName string, processors []chunk.IndexEntryProcessor) error { |
| 74 | + projection := hashKey + "," + rangeKey |
| 75 | + |
| 76 | + sm := &seriesMap{ // new map per table |
| 77 | + seriesProcessed: make(map[string]sha256Set), |
| 78 | + } |
| 79 | + |
| 80 | + var readerGroup errgroup.Group |
| 81 | + // Start a goroutine for each processor |
| 82 | + for i, processor := range processors { |
| 83 | + segment, processor := i, processor // https://golang.org/doc/faq#closures_and_goroutines |
| 84 | + readerGroup.Go(func() error { |
| 85 | + input := &dynamodb.ScanInput{ |
| 86 | + TableName: aws.String(tableName), |
| 87 | + ProjectionExpression: aws.String(projection), |
| 88 | + Segment: aws.Int64(int64(segment)), |
| 89 | + TotalSegments: aws.Int64(int64(len(processors))), |
| 90 | + ReturnConsumedCapacity: aws.String(dynamodb.ReturnConsumedCapacityTotal), |
| 91 | + } |
| 92 | + withRetrys := func(req *request.Request) { |
| 93 | + req.Retryer = client.DefaultRetryer{NumMaxRetries: r.maxRetries} |
| 94 | + } |
| 95 | + err := r.DynamoDB.ScanPagesWithContext(ctx, input, func(page *dynamodb.ScanOutput, lastPage bool) bool { |
| 96 | + if cc := page.ConsumedCapacity; cc != nil { |
| 97 | + r.metrics.dynamoConsumedCapacity.WithLabelValues("DynamoDB.ScanTable", *cc.TableName). |
| 98 | + Add(float64(*cc.CapacityUnits)) |
| 99 | + } |
| 100 | + r.processPage(ctx, sm, processor, tableName, page) |
| 101 | + return true |
| 102 | + }, withRetrys) |
| 103 | + if err != nil { |
| 104 | + return err |
| 105 | + } |
| 106 | + processor.Flush() |
| 107 | + level.Info(r.log).Log("msg", "Segment finished", "segment", segment) |
| 108 | + return nil |
| 109 | + }) |
| 110 | + } |
| 111 | + // Wait until all reader segments have finished |
| 112 | + outerErr := readerGroup.Wait() |
| 113 | + if outerErr != nil { |
| 114 | + return outerErr |
| 115 | + } |
| 116 | + return nil |
| 117 | +} |
| 118 | + |
| 119 | +func (r *dynamodbIndexReader) processPage(ctx context.Context, sm *seriesMap, processor chunk.IndexEntryProcessor, tableName string, page *dynamodb.ScanOutput) { |
| 120 | + for _, item := range page.Items { |
| 121 | + r.rowsRead.Inc() |
| 122 | + rangeValue := item[rangeKey].B |
| 123 | + if !isSeriesIndexEntry(rangeValue) { |
| 124 | + continue |
| 125 | + } |
| 126 | + hashValue := aws.StringValue(item[hashKey].S) |
| 127 | + orgStr, day, seriesID, err := decodeHashValue(hashValue) |
| 128 | + if err != nil { |
| 129 | + level.Error(r.log).Log("msg", "Failed to decode hash value", "err", err) |
| 130 | + continue |
| 131 | + } |
| 132 | + if !processor.AcceptUser(orgStr) { |
| 133 | + continue |
| 134 | + } |
| 135 | + |
| 136 | + bucketHashKey := orgStr + ":" + day // from v9Entries.GetChunkWriteEntries() |
| 137 | + |
| 138 | + // Check whether we have already processed this series |
| 139 | + // via two-step lookup: first by tenant/day bucket, then by series |
| 140 | + var seriesSha256 sha256 |
| 141 | + err = decodeBase64(seriesSha256[:], seriesID) |
| 142 | + if err != nil { |
| 143 | + level.Error(r.log).Log("msg", "Failed to decode series ID", "err", err) |
| 144 | + continue |
| 145 | + } |
| 146 | + sm.mutex.Lock() |
| 147 | + shaSet := sm.seriesProcessed[bucketHashKey] |
| 148 | + if shaSet.series == nil { |
| 149 | + shaSet.series = make(map[sha256]struct{}) |
| 150 | + sm.seriesProcessed[bucketHashKey] = shaSet |
| 151 | + } |
| 152 | + if _, exists := shaSet.series[seriesSha256]; exists { |
| 153 | + sm.mutex.Unlock() |
| 154 | + continue |
| 155 | + } |
| 156 | + // mark it as 'seen already' |
| 157 | + shaSet.series[seriesSha256] = struct{}{} |
| 158 | + sm.mutex.Unlock() |
| 159 | + |
| 160 | + err = r.queryChunkEntriesForSeries(ctx, processor, tableName, bucketHashKey+":"+seriesID) |
| 161 | + if err != nil { |
| 162 | + level.Error(r.log).Log("msg", "error while reading series", "err", err) |
| 163 | + return |
| 164 | + } |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +func decodeBase64(dst []byte, value string) error { |
| 169 | + n, err := base64.RawStdEncoding.Decode(dst, []byte(value)) |
| 170 | + if err != nil { |
| 171 | + return errors.Wrap(err, "unable to decode sha256") |
| 172 | + } |
| 173 | + if n != len(dst) { |
| 174 | + return errors.Wrapf(err, "seriesID has unexpected length; raw value %q", value) |
| 175 | + } |
| 176 | + return nil |
| 177 | +} |
| 178 | + |
| 179 | +func (r *dynamodbIndexReader) queryChunkEntriesForSeries(ctx context.Context, processor chunk.IndexEntryProcessor, tableName, queryHashKey string) error { |
| 180 | + // DynamoDB query which just says "all rows with hashKey X" |
| 181 | + // This is hard-coded for schema v9 |
| 182 | + input := &dynamodb.QueryInput{ |
| 183 | + TableName: aws.String(tableName), |
| 184 | + KeyConditions: map[string]*dynamodb.Condition{ |
| 185 | + hashKey: { |
| 186 | + AttributeValueList: []*dynamodb.AttributeValue{ |
| 187 | + {S: aws.String(queryHashKey)}, |
| 188 | + }, |
| 189 | + ComparisonOperator: aws.String(dynamodb.ComparisonOperatorEq), |
| 190 | + }, |
| 191 | + }, |
| 192 | + ReturnConsumedCapacity: aws.String(dynamodb.ReturnConsumedCapacityTotal), |
| 193 | + } |
| 194 | + withRetrys := func(req *request.Request) { |
| 195 | + req.Retryer = client.DefaultRetryer{NumMaxRetries: r.maxRetries} |
| 196 | + } |
| 197 | + var result error |
| 198 | + err := r.DynamoDB.QueryPagesWithContext(ctx, input, func(output *dynamodb.QueryOutput, _ bool) bool { |
| 199 | + if cc := output.ConsumedCapacity; cc != nil { |
| 200 | + r.metrics.dynamoConsumedCapacity.WithLabelValues("DynamoDB.QueryPages", *cc.TableName). |
| 201 | + Add(float64(*cc.CapacityUnits)) |
| 202 | + } |
| 203 | + |
| 204 | + for _, item := range output.Items { |
| 205 | + err := processor.ProcessIndexEntry(chunk.IndexEntry{ |
| 206 | + TableName: tableName, |
| 207 | + HashValue: aws.StringValue(item[hashKey].S), |
| 208 | + RangeValue: item[rangeKey].B}) |
| 209 | + if err != nil { |
| 210 | + result = errors.Wrap(err, "processor error") |
| 211 | + return false |
| 212 | + } |
| 213 | + } |
| 214 | + return true |
| 215 | + }, withRetrys) |
| 216 | + if err != nil { |
| 217 | + return errors.Wrap(err, "DynamoDB error") |
| 218 | + } |
| 219 | + return result |
| 220 | +} |
| 221 | + |
| 222 | +func isSeriesIndexEntry(rangeValue []byte) bool { |
| 223 | + const chunkTimeRangeKeyV3 = '3' // copied from pkg/chunk/schema.go |
| 224 | + return len(rangeValue) > 2 && rangeValue[len(rangeValue)-2] == chunkTimeRangeKeyV3 |
| 225 | +} |
| 226 | + |
| 227 | +func decodeHashValue(hashValue string) (orgStr, day, seriesID string, err error) { |
| 228 | + hashParts := strings.SplitN(hashValue, ":", 3) |
| 229 | + if len(hashParts) != 3 { |
| 230 | + err = fmt.Errorf("unrecognized hash value: %q", hashValue) |
| 231 | + return |
| 232 | + } |
| 233 | + orgStr = hashParts[0] |
| 234 | + day = hashParts[1] |
| 235 | + seriesID = hashParts[2] |
| 236 | + return |
| 237 | +} |
0 commit comments