/
metadata_store.go
510 lines (445 loc) · 16 KB
/
metadata_store.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cassandra
import (
"context"
"fmt"
"go.temporal.io/api/serviceerror"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
p "go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/persistence/nosql/nosqlplugin/cassandra/gocql"
"go.temporal.io/server/common/primitives"
)
const (
constNamespacePartition = 0
namespaceMetadataRecordName = "temporal-namespace-metadata"
)
const (
templateCreateNamespaceQuery = `INSERT INTO namespaces_by_id (` +
`id, name) ` +
`VALUES(?, ?) IF NOT EXISTS`
templateGetNamespaceQuery = `SELECT name ` +
`FROM namespaces_by_id ` +
`WHERE id = ?`
templateDeleteNamespaceQuery = `DELETE FROM namespaces_by_id ` +
`WHERE id = ?`
templateNamespaceColumns = `id, name, detail, detail_encoding, notification_version, is_global_namespace`
templateCreateNamespaceByNameQueryWithinBatchV2 = `INSERT INTO namespaces ` +
`( namespaces_partition, ` + templateNamespaceColumns + `) ` +
`VALUES(?, ?, ?, ?, ?, ?, ?) IF NOT EXISTS`
templateGetNamespaceByNameQueryV2 = templateListNamespaceQueryV2 + `and name = ?`
templateUpdateNamespaceByNameQueryWithinBatchV2 = `UPDATE namespaces ` +
`SET detail = ? ,` +
`detail_encoding = ? ,` +
`is_global_namespace = ? ,` +
`notification_version = ? ` +
`WHERE namespaces_partition = ? ` +
`and name = ?`
templateGetMetadataQueryV2 = `SELECT notification_version ` +
`FROM namespaces ` +
`WHERE namespaces_partition = ? ` +
`and name = ? `
templateUpdateMetadataQueryWithinBatchV2 = `UPDATE namespaces ` +
`SET notification_version = ? ` +
`WHERE namespaces_partition = ? ` +
`and name = ? ` +
`IF notification_version = ? `
templateDeleteNamespaceByNameQueryV2 = `DELETE FROM namespaces ` +
`WHERE namespaces_partition = ? ` +
`and name = ?`
templateListNamespaceQueryV2 = `SELECT ` +
templateNamespaceColumns +
` FROM namespaces ` +
`WHERE namespaces_partition = ? `
templateUpdateNamespaceByIdQuery = `UPDATE namespaces_by_id ` +
`SET name = ? ` +
`WHERE id = ?`
)
type (
MetadataStore struct {
session gocql.Session
logger log.Logger
currentClusterName string
}
)
// NewMetadataStore is used to create an instance of the Namespace MetadataStore implementation
func NewMetadataStore(
currentClusterName string,
session gocql.Session,
logger log.Logger,
) (p.MetadataStore, error) {
return &MetadataStore{
currentClusterName: currentClusterName,
session: session,
logger: logger,
}, nil
}
// CreateNamespace create a namespace
// Cassandra does not support conditional updates across multiple tables. For this reason we have to first insert into
// 'Namespaces' table and then do a conditional insert into namespaces_by_name table. If the conditional write fails we
// delete the orphaned entry from namespaces table. There is a chance delete entry could fail and we never delete the
// orphaned entry from namespaces table. We might need a background job to delete those orphaned record.
func (m *MetadataStore) CreateNamespace(
ctx context.Context,
request *p.InternalCreateNamespaceRequest,
) (*p.CreateNamespaceResponse, error) {
query := m.session.Query(templateCreateNamespaceQuery, request.ID, request.Name).WithContext(ctx)
existingRow := make(map[string]interface{})
applied, err := query.MapScanCAS(existingRow)
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf("CreateNamespace operation failed. Inserting into namespaces table. Error: %v", err))
}
if !applied {
// if the id with the same name exists in `namespaces_by_id`, fall through and either add a row in `namespaces` table
// or fail if name exists in that table already. This is to make sure we do not end up with a row in `namespaces_by_id`
// table and no entry in `namespaces` table
if name, ok := existingRow["name"]; !ok || name != request.Name {
return nil, serviceerror.NewNamespaceAlreadyExists("CreateNamespace operation failed because of uuid collision.")
}
}
return m.CreateNamespaceInV2Table(ctx, request)
}
// CreateNamespaceInV2Table is the temporary function used by namespace v1 -> v2 migration
func (m *MetadataStore) CreateNamespaceInV2Table(
ctx context.Context,
request *p.InternalCreateNamespaceRequest,
) (*p.CreateNamespaceResponse, error) {
metadata, err := m.GetMetadata(ctx)
if err != nil {
return nil, err
}
batch := m.session.NewBatch(gocql.LoggedBatch).WithContext(ctx)
batch.Query(templateCreateNamespaceByNameQueryWithinBatchV2,
constNamespacePartition,
request.ID,
request.Name,
request.Namespace.Data,
request.Namespace.EncodingType.String(),
metadata.NotificationVersion,
request.IsGlobal,
)
m.updateMetadataBatch(batch, metadata.NotificationVersion)
previous := make(map[string]interface{})
applied, iter, err := m.session.MapExecuteBatchCAS(batch, previous)
deleteOrphanNamespace := func() {
// Delete namespace from `namespaces_by_id`
if errDelete := m.session.Query(templateDeleteNamespaceQuery, request.ID).WithContext(ctx).Exec(); errDelete != nil {
m.logger.Warn("Unable to delete orphan namespace record. Error", tag.Error(errDelete))
}
}
if err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf("CreateNamespace operation failed. Inserting into namespaces table. Error: %v", err))
}
defer func() { _ = iter.Close() }()
if !applied {
// if conditional failure is due to a duplicate name in namespaces table
if name, ok := previous["name"]; ok && name == request.Name {
existingID := request.ID
if id, ok := previous["id"]; ok && gocql.UUIDToString(id) != request.ID {
existingID = gocql.UUIDToString(id)
// Delete orphan namespace record before returning back to user
deleteOrphanNamespace()
}
msg := fmt.Sprintf("Namespace already exists. NamespaceId: %v", existingID)
return nil, serviceerror.NewNamespaceAlreadyExists(msg)
}
// If namespace does not exist already and applied is false,
// notification_version does not match our expectations and it's conditional failure.
// Delete orphan namespace record before returning back to user
deleteOrphanNamespace()
return nil, serviceerror.NewUnavailable("CreateNamespace operation failed because of conditional failure.")
}
return &p.CreateNamespaceResponse{ID: request.ID}, nil
}
func (m *MetadataStore) UpdateNamespace(
ctx context.Context,
request *p.InternalUpdateNamespaceRequest,
) error {
batch := m.session.NewBatch(gocql.LoggedBatch).WithContext(ctx)
batch.Query(templateUpdateNamespaceByNameQueryWithinBatchV2,
request.Namespace.Data,
request.Namespace.EncodingType.String(),
request.IsGlobal,
request.NotificationVersion,
constNamespacePartition,
request.Name,
)
m.updateMetadataBatch(batch, request.NotificationVersion)
previous := make(map[string]interface{})
applied, iter, err := m.session.MapExecuteBatchCAS(batch, previous)
if err != nil {
return serviceerror.NewUnavailable(fmt.Sprintf("UpdateNamespace operation failed. Error: %v", err))
}
defer func() { _ = iter.Close() }()
if !applied {
return serviceerror.NewUnavailable("UpdateNamespace operation failed because of conditional failure.")
}
return nil
}
// RenameNamespace should be used with caution.
// Not every namespace can be renamed because namespace name are stored in the database.
// It may leave database in inconsistent state and must be retried until success.
// Step 1. Update row in `namespaces_by_id` table with the new name.
// Step 2. Batch of:
//
// Insert row into `namespaces` table with new name and new `notification_version`.
// Delete row from `namespaces` table with old name.
// Update `notification_version` in metadata row.
//
// NOTE: `namespaces_by_id` is currently used only for `DescribeNamespace` API and namespace Id collision check.
func (m *MetadataStore) RenameNamespace(
ctx context.Context,
request *p.InternalRenameNamespaceRequest,
) error {
// Step 1.
if updateErr := m.session.Query(templateUpdateNamespaceByIdQuery,
request.Name,
request.Id,
).WithContext(ctx).Exec(); updateErr != nil {
return serviceerror.NewUnavailable(fmt.Sprintf("RenameNamespace operation failed to update 'namespaces_by_id' table. Error: %v", updateErr))
}
// Step 2.
batch := m.session.NewBatch(gocql.LoggedBatch).WithContext(ctx)
batch.Query(templateCreateNamespaceByNameQueryWithinBatchV2,
constNamespacePartition,
request.Id,
request.Name,
request.Namespace.Data,
request.Namespace.EncodingType.String(),
request.NotificationVersion,
request.IsGlobal,
)
batch.Query(templateDeleteNamespaceByNameQueryV2,
constNamespacePartition,
request.PreviousName,
)
m.updateMetadataBatch(batch, request.NotificationVersion)
previous := make(map[string]interface{})
applied, iter, err := m.session.MapExecuteBatchCAS(batch, previous)
if err != nil {
return serviceerror.NewUnavailable(fmt.Sprintf("RenameNamespace operation failed. Error: %v", err))
}
defer func() { _ = iter.Close() }()
if !applied {
return serviceerror.NewUnavailable("RenameNamespace operation failed because of conditional failure.")
}
return nil
}
func (m *MetadataStore) GetNamespace(
ctx context.Context,
request *p.GetNamespaceRequest,
) (*p.InternalGetNamespaceResponse, error) {
var query gocql.Query
var err error
var detail []byte
var detailEncoding string
var notificationVersion int64
var isGlobalNamespace bool
if len(request.ID) > 0 && len(request.Name) > 0 {
return nil, serviceerror.NewInvalidArgument("GetNamespace operation failed. Both ID and Name specified in request.Namespace.")
} else if len(request.ID) == 0 && len(request.Name) == 0 {
return nil, serviceerror.NewInvalidArgument("GetNamespace operation failed. Both ID and Name are empty.")
}
handleError := func(name string, ID string, err error) error {
identity := name
if gocql.IsNotFoundError(err) {
if len(ID) > 0 {
identity = ID
}
return serviceerror.NewNamespaceNotFound(identity)
}
return serviceerror.NewUnavailable(fmt.Sprintf("GetNamespace operation failed. Error %v", err))
}
namespace := request.Name
if len(request.ID) > 0 {
query = m.session.Query(templateGetNamespaceQuery, request.ID).WithContext(ctx)
err = query.Scan(&namespace)
if err != nil {
return nil, handleError(request.Name, request.ID, err)
}
}
query = m.session.Query(templateGetNamespaceByNameQueryV2, constNamespacePartition, namespace).WithContext(ctx)
err = query.Scan(
nil,
nil,
&detail,
&detailEncoding,
¬ificationVersion,
&isGlobalNamespace,
)
if err != nil {
return nil, handleError(request.Name, request.ID, err)
}
return &p.InternalGetNamespaceResponse{
Namespace: p.NewDataBlob(detail, detailEncoding),
IsGlobal: isGlobalNamespace,
NotificationVersion: notificationVersion,
}, nil
}
func (m *MetadataStore) ListNamespaces(
ctx context.Context,
request *p.InternalListNamespacesRequest,
) (*p.InternalListNamespacesResponse, error) {
query := m.session.Query(templateListNamespaceQueryV2, constNamespacePartition).WithContext(ctx)
pageSize := request.PageSize
nextPageToken := request.NextPageToken
response := &p.InternalListNamespacesResponse{}
for {
iter := query.PageSize(pageSize).PageState(nextPageToken).Iter()
skippedRows := 0
for {
var name string
var detail []byte
var detailEncoding string
var notificationVersion int64
var isGlobal bool
if !iter.Scan(
nil,
&name,
&detail,
&detailEncoding,
¬ificationVersion,
&isGlobal,
) {
// done iterating over all namespaces in this page
break
}
// do not include the metadata record
if name == namespaceMetadataRecordName {
skippedRows++
continue
}
response.Namespaces = append(response.Namespaces, &p.InternalGetNamespaceResponse{
Namespace: p.NewDataBlob(detail, detailEncoding),
IsGlobal: isGlobal,
NotificationVersion: notificationVersion,
})
}
if len(iter.PageState()) > 0 {
nextPageToken = iter.PageState()
} else {
nextPageToken = nil
}
if err := iter.Close(); err != nil {
return nil, serviceerror.NewUnavailable(fmt.Sprintf("ListNamespaces operation failed. Error: %v", err))
}
if len(nextPageToken) == 0 {
// No more records in DB.
break
}
if skippedRows == 0 {
break
}
pageSize = skippedRows
}
response.NextPageToken = nextPageToken
return response, nil
}
func (m *MetadataStore) DeleteNamespace(
ctx context.Context,
request *p.DeleteNamespaceRequest,
) error {
var name string
query := m.session.Query(templateGetNamespaceQuery, request.ID).WithContext(ctx)
err := query.Scan(&name)
if err != nil {
if gocql.IsNotFoundError(err) {
return nil
}
return err
}
parsedID, err := primitives.ParseUUID(request.ID)
if err != nil {
return err
}
return m.deleteNamespace(ctx, name, parsedID)
}
func (m *MetadataStore) DeleteNamespaceByName(
ctx context.Context,
request *p.DeleteNamespaceByNameRequest,
) error {
var ID []byte
query := m.session.Query(templateGetNamespaceByNameQueryV2, constNamespacePartition, request.Name).WithContext(ctx)
err := query.Scan(&ID, nil, nil, nil, nil, nil)
if err != nil {
if gocql.IsNotFoundError(err) {
return nil
}
return err
}
return m.deleteNamespace(ctx, request.Name, ID)
}
func (m *MetadataStore) GetMetadata(
ctx context.Context,
) (*p.GetMetadataResponse, error) {
var notificationVersion int64
query := m.session.Query(templateGetMetadataQueryV2, constNamespacePartition, namespaceMetadataRecordName).WithContext(ctx)
err := query.Scan(¬ificationVersion)
if err != nil {
if gocql.IsNotFoundError(err) {
// this error can be thrown in the very beginning,
// i.e. when namespaces is initialized
return &p.GetMetadataResponse{NotificationVersion: 0}, nil
}
return nil, err
}
return &p.GetMetadataResponse{NotificationVersion: notificationVersion}, nil
}
func (m *MetadataStore) updateMetadataBatch(
batch gocql.Batch,
notificationVersion int64,
) {
var nextVersion int64 = 1
var currentVersion *int64
if notificationVersion > 0 {
nextVersion = notificationVersion + 1
currentVersion = ¬ificationVersion
}
batch.Query(templateUpdateMetadataQueryWithinBatchV2,
nextVersion,
constNamespacePartition,
namespaceMetadataRecordName,
currentVersion,
)
}
func (m *MetadataStore) deleteNamespace(ctx context.Context, name string, ID []byte) error {
query := m.session.Query(templateDeleteNamespaceByNameQueryV2, constNamespacePartition, name).WithContext(ctx)
if err := query.Exec(); err != nil {
return serviceerror.NewUnavailable(fmt.Sprintf("DeleteNamespaceByName operation failed. Error %v", err))
}
query = m.session.Query(templateDeleteNamespaceQuery, ID).WithContext(ctx)
if err := query.Exec(); err != nil {
return serviceerror.NewUnavailable(fmt.Sprintf("DeleteNamespace operation failed. Error %v", err))
}
return nil
}
func (m *MetadataStore) GetName() string {
return cassandraPersistenceName
}
func (m *MetadataStore) Close() {
if m.session != nil {
m.session.Close()
}
}