|
| 1 | +package chunk |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/binary" |
| 6 | + "encoding/hex" |
| 7 | + "errors" |
| 8 | + "flag" |
| 9 | + "fmt" |
| 10 | + "hash/fnv" |
| 11 | + "strconv" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/prometheus/common/model" |
| 16 | + "github.com/prometheus/prometheus/pkg/labels" |
| 17 | +) |
| 18 | + |
| 19 | +type DeleteRequestStatus string |
| 20 | + |
| 21 | +const ( |
| 22 | + StatusReceived DeleteRequestStatus = "received" |
| 23 | + StatusBuildingPlan DeleteRequestStatus = "buildingPlan" |
| 24 | + StatusDeleting DeleteRequestStatus = "deleting" |
| 25 | + StatusProcessed DeleteRequestStatus = "processed" |
| 26 | + |
| 27 | + separator = "\000" // separator for series selectors in delete requests |
| 28 | +) |
| 29 | + |
| 30 | +var ( |
| 31 | + pendingDeleteRequestStatuses = []DeleteRequestStatus{StatusReceived, StatusBuildingPlan, StatusDeleting} |
| 32 | + |
| 33 | + ErrDeleteRequestNotFound = errors.New("could not find matching delete request") |
| 34 | +) |
| 35 | + |
| 36 | +// DeleteRequest holds all the details about a delete request |
| 37 | +type DeleteRequest struct { |
| 38 | + RequestID string `json:"request_id"` |
| 39 | + UserID string `json:"-"` |
| 40 | + StartTime model.Time `json:"start_time"` |
| 41 | + EndTime model.Time `json:"end_time"` |
| 42 | + Selectors []string `json:"selectors"` |
| 43 | + Status DeleteRequestStatus `json:"status"` |
| 44 | + Matchers [][]*labels.Matcher `json:"-"` |
| 45 | + CreatedAt model.Time `json:"created_at"` |
| 46 | +} |
| 47 | + |
| 48 | +// DeleteStore provides all the methods required to manage lifecycle of delete request and things related to it |
| 49 | +type DeleteStore struct { |
| 50 | + cfg DeleteStoreConfig |
| 51 | + indexClient IndexClient |
| 52 | +} |
| 53 | + |
| 54 | +// DeleteStoreConfig holds configuration for delete store |
| 55 | +type DeleteStoreConfig struct { |
| 56 | + Store string `yaml:"store"` |
| 57 | + RequestsTableName string `yaml:"requests_table_name"` |
| 58 | +} |
| 59 | + |
| 60 | +// RegisterFlags adds the flags required to configure this flag set. |
| 61 | +func (cfg *DeleteStoreConfig) RegisterFlags(f *flag.FlagSet) { |
| 62 | + f.StringVar(&cfg.Store, "deletes.store", "", "Store for keeping delete request") |
| 63 | + f.StringVar(&cfg.RequestsTableName, "deletes.requests-table-name", "delete_requests", "Name of the table which stores delete requests") |
| 64 | +} |
| 65 | + |
| 66 | +// NewDeleteStore creates a store for managing delete requests |
| 67 | +func NewDeleteStore(cfg DeleteStoreConfig, indexClient IndexClient) (*DeleteStore, error) { |
| 68 | + ds := DeleteStore{ |
| 69 | + cfg: cfg, |
| 70 | + indexClient: indexClient, |
| 71 | + } |
| 72 | + |
| 73 | + return &ds, nil |
| 74 | +} |
| 75 | + |
| 76 | +// Add creates entries for a new delete request |
| 77 | +func (ds *DeleteStore) AddDeleteRequest(ctx context.Context, userID string, startTime, endTime model.Time, selectors []string) error { |
| 78 | + requestID := generateUniqueID(userID, selectors) |
| 79 | + |
| 80 | + for { |
| 81 | + _, err := ds.GetDeleteRequest(ctx, userID, string(requestID)) |
| 82 | + if err != nil { |
| 83 | + if err == ErrDeleteRequestNotFound { |
| 84 | + break |
| 85 | + } |
| 86 | + return err |
| 87 | + } |
| 88 | + |
| 89 | + // we have a collision here, lets recreate a new requestID and check for collision |
| 90 | + time.Sleep(time.Millisecond) |
| 91 | + requestID = generateUniqueID(userID, selectors) |
| 92 | + } |
| 93 | + |
| 94 | + // userID, requestID |
| 95 | + userIDAndRequestID := fmt.Sprintf("%s:%s", userID, requestID) |
| 96 | + |
| 97 | + // Add an entry with userID, requestID as range key and status as value to make it easy to manage and lookup status |
| 98 | + // We don't want to set anything in hash key here since we would want to find delete requests by just status |
| 99 | + writeBatch := ds.indexClient.NewWriteBatch() |
| 100 | + writeBatch.Add(ds.cfg.RequestsTableName, "", []byte(userIDAndRequestID), []byte(StatusReceived)) |
| 101 | + |
| 102 | + // Add another entry with additional details like creation time, time range of delete request and selectors in value |
| 103 | + rangeValue := fmt.Sprintf("%x:%x:%x", int64(model.Now()), int64(startTime), int64(endTime)) |
| 104 | + writeBatch.Add(ds.cfg.RequestsTableName, userIDAndRequestID, []byte(rangeValue), []byte(strings.Join(selectors, separator))) |
| 105 | + |
| 106 | + return ds.indexClient.BatchWrite(ctx, writeBatch) |
| 107 | +} |
| 108 | + |
| 109 | +// GetDeleteRequestsByStatus returns all delete requests for given status |
| 110 | +func (ds *DeleteStore) GetDeleteRequestsByStatus(ctx context.Context, status DeleteRequestStatus) ([]DeleteRequest, error) { |
| 111 | + return ds.queryDeleteRequests(ctx, []IndexQuery{{TableName: ds.cfg.RequestsTableName, ValueEqual: []byte(status)}}) |
| 112 | +} |
| 113 | + |
| 114 | +// GetDeleteRequestsForUserByStatus returns all delete requests for a user with given status |
| 115 | +func (ds *DeleteStore) GetDeleteRequestsForUserByStatus(ctx context.Context, userID string, status DeleteRequestStatus) ([]DeleteRequest, error) { |
| 116 | + return ds.queryDeleteRequests(ctx, []IndexQuery{ |
| 117 | + {TableName: ds.cfg.RequestsTableName, RangeValuePrefix: []byte(userID), ValueEqual: []byte(status)}, |
| 118 | + }) |
| 119 | +} |
| 120 | + |
| 121 | +// GetAllDeleteRequestsForUser returns all delete requests for a user |
| 122 | +func (ds *DeleteStore) GetAllDeleteRequestsForUser(ctx context.Context, userID string) ([]DeleteRequest, error) { |
| 123 | + return ds.queryDeleteRequests(ctx, []IndexQuery{ |
| 124 | + {TableName: ds.cfg.RequestsTableName, RangeValuePrefix: []byte(userID)}, |
| 125 | + }) |
| 126 | +} |
| 127 | + |
| 128 | +// UpdateStatus updates status of a delete request |
| 129 | +func (ds *DeleteStore) UpdateStatus(ctx context.Context, userID, requestID string, newStatus DeleteRequestStatus) error { |
| 130 | + userIDAndRequestID := fmt.Sprintf("%s:%s", userID, requestID) |
| 131 | + |
| 132 | + writeBatch := ds.indexClient.NewWriteBatch() |
| 133 | + writeBatch.Add(ds.cfg.RequestsTableName, "", []byte(userIDAndRequestID), []byte(newStatus)) |
| 134 | + |
| 135 | + return ds.indexClient.BatchWrite(ctx, writeBatch) |
| 136 | +} |
| 137 | + |
| 138 | +// GetDeleteRequest returns delete request with given requestID |
| 139 | +func (ds *DeleteStore) GetDeleteRequest(ctx context.Context, userID, requestID string) (*DeleteRequest, error) { |
| 140 | + userIDAndRequestID := fmt.Sprintf("%s:%s", userID, requestID) |
| 141 | + |
| 142 | + deleteRequests, err := ds.queryDeleteRequests(ctx, []IndexQuery{ |
| 143 | + {TableName: ds.cfg.RequestsTableName, RangeValuePrefix: []byte(userIDAndRequestID)}, |
| 144 | + }) |
| 145 | + |
| 146 | + if err != nil { |
| 147 | + return nil, err |
| 148 | + } |
| 149 | + |
| 150 | + if len(deleteRequests) == 0 { |
| 151 | + return nil, ErrDeleteRequestNotFound |
| 152 | + } |
| 153 | + |
| 154 | + return &deleteRequests[0], nil |
| 155 | +} |
| 156 | + |
| 157 | +// GetPendingDeleteRequestsForUser returns all delete requests for a user which are not processed |
| 158 | +func (ds *DeleteStore) GetPendingDeleteRequestsForUser(ctx context.Context, userID string) ([]DeleteRequest, error) { |
| 159 | + pendingDeleteRequests := []DeleteRequest{} |
| 160 | + for _, status := range pendingDeleteRequestStatuses { |
| 161 | + deleteRequests, err := ds.GetDeleteRequestsForUserByStatus(ctx, userID, status) |
| 162 | + if err != nil { |
| 163 | + return nil, err |
| 164 | + } |
| 165 | + |
| 166 | + pendingDeleteRequests = append(pendingDeleteRequests, deleteRequests...) |
| 167 | + } |
| 168 | + |
| 169 | + return pendingDeleteRequests, nil |
| 170 | +} |
| 171 | + |
| 172 | +func (ds *DeleteStore) queryDeleteRequests(ctx context.Context, deleteQuery []IndexQuery) ([]DeleteRequest, error) { |
| 173 | + deleteRequests := []DeleteRequest{} |
| 174 | + err := ds.indexClient.QueryPages(ctx, deleteQuery, func(query IndexQuery, batch ReadBatch) (shouldContinue bool) { |
| 175 | + itr := batch.Iterator() |
| 176 | + for itr.Next() { |
| 177 | + userID, requestID := splitUserIDAndRequestID(string(itr.RangeValue())) |
| 178 | + |
| 179 | + deleteRequests = append(deleteRequests, DeleteRequest{ |
| 180 | + UserID: userID, |
| 181 | + RequestID: requestID, |
| 182 | + Status: DeleteRequestStatus(itr.Value()), |
| 183 | + }) |
| 184 | + } |
| 185 | + return true |
| 186 | + }) |
| 187 | + if err != nil { |
| 188 | + return nil, err |
| 189 | + } |
| 190 | + |
| 191 | + for i, deleteRequest := range deleteRequests { |
| 192 | + deleteRequestQuery := []IndexQuery{{TableName: ds.cfg.RequestsTableName, HashValue: fmt.Sprintf("%s:%s", deleteRequest.UserID, deleteRequest.RequestID)}} |
| 193 | + |
| 194 | + var parseError error |
| 195 | + err := ds.indexClient.QueryPages(ctx, deleteRequestQuery, func(query IndexQuery, batch ReadBatch) (shouldContinue bool) { |
| 196 | + itr := batch.Iterator() |
| 197 | + itr.Next() |
| 198 | + |
| 199 | + deleteRequest, err = parseDeleteRequestTimestamps(itr.RangeValue(), deleteRequest) |
| 200 | + if err != nil { |
| 201 | + parseError = err |
| 202 | + return false |
| 203 | + } |
| 204 | + |
| 205 | + deleteRequest.Selectors = strings.Split(string(itr.Value()), separator) |
| 206 | + deleteRequests[i] = deleteRequest |
| 207 | + |
| 208 | + return true |
| 209 | + }) |
| 210 | + |
| 211 | + if err != nil { |
| 212 | + return nil, err |
| 213 | + } |
| 214 | + |
| 215 | + if parseError != nil { |
| 216 | + return nil, parseError |
| 217 | + } |
| 218 | + } |
| 219 | + |
| 220 | + return deleteRequests, nil |
| 221 | +} |
| 222 | + |
| 223 | +func parseDeleteRequestTimestamps(rangeValue []byte, deleteRequest DeleteRequest) (DeleteRequest, error) { |
| 224 | + hexParts := strings.Split(string(rangeValue), ":") |
| 225 | + if len(hexParts) != 3 { |
| 226 | + return deleteRequest, errors.New("invalid key in parsing delete request lookup response") |
| 227 | + } |
| 228 | + |
| 229 | + createdAt, err := strconv.ParseInt(hexParts[0], 16, 64) |
| 230 | + if err != nil { |
| 231 | + return deleteRequest, err |
| 232 | + } |
| 233 | + |
| 234 | + from, err := strconv.ParseInt(hexParts[1], 16, 64) |
| 235 | + if err != nil { |
| 236 | + return deleteRequest, err |
| 237 | + |
| 238 | + } |
| 239 | + through, err := strconv.ParseInt(hexParts[2], 16, 64) |
| 240 | + if err != nil { |
| 241 | + return deleteRequest, err |
| 242 | + |
| 243 | + } |
| 244 | + |
| 245 | + deleteRequest.CreatedAt = model.Time(createdAt) |
| 246 | + deleteRequest.StartTime = model.Time(from) |
| 247 | + deleteRequest.EndTime = model.Time(through) |
| 248 | + |
| 249 | + return deleteRequest, nil |
| 250 | +} |
| 251 | + |
| 252 | +// An id is useful in managing delete requests |
| 253 | +func generateUniqueID(orgID string, selectors []string) []byte { |
| 254 | + uniqueID := fnv.New32() |
| 255 | + _, _ = uniqueID.Write([]byte(orgID)) |
| 256 | + |
| 257 | + timeNow := make([]byte, 8) |
| 258 | + binary.LittleEndian.PutUint64(timeNow, uint64(time.Now().UnixNano())) |
| 259 | + _, _ = uniqueID.Write(timeNow) |
| 260 | + |
| 261 | + for _, selector := range selectors { |
| 262 | + _, _ = uniqueID.Write([]byte(selector)) |
| 263 | + } |
| 264 | + |
| 265 | + return encodeUniqueID(uniqueID.Sum32()) |
| 266 | +} |
| 267 | + |
| 268 | +func encodeUniqueID(t uint32) []byte { |
| 269 | + throughBytes := make([]byte, 4) |
| 270 | + binary.BigEndian.PutUint32(throughBytes, t) |
| 271 | + encodedThroughBytes := make([]byte, 8) |
| 272 | + hex.Encode(encodedThroughBytes, throughBytes) |
| 273 | + return encodedThroughBytes |
| 274 | +} |
| 275 | + |
| 276 | +func splitUserIDAndRequestID(rangeValue string) (userID, requestID string) { |
| 277 | + lastIndex := strings.LastIndex(rangeValue, ":") |
| 278 | + |
| 279 | + userID = rangeValue[:lastIndex] |
| 280 | + requestID = rangeValue[lastIndex+1:] |
| 281 | + |
| 282 | + return |
| 283 | +} |
0 commit comments