-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a firestore key migration to Teleport 17 #46472
Merged
Merged
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
030072c
Add a firestore key migration to Teleport 17
tigrato a4e45a9
force key to be array
tigrato ac792a4
add rate limited bucket
tigrato 29d14b7
reduce limit
tigrato c2f93ec
add migration in its own goroutine and use optimistic locking
tigrato f74a94d
add deprecation release
tigrato 3fadc99
retry migration every 12h (max)
tigrato a26468f
add migration tests
tigrato 1856068
Merge branch 'master' into tigrato/firestore-migration
tigrato 503efb4
fix typo
tigrato File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
/* | ||
* Teleport | ||
* Copyright (C) 2023 Gravitational, Inc. | ||
* | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU Affero General Public License as published by | ||
* the Free Software Foundation, either version 3 of the License, or | ||
* (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU Affero General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Affero General Public License | ||
* along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
package firestore | ||
|
||
import ( | ||
"context" | ||
"time" | ||
|
||
"cloud.google.com/go/firestore" | ||
"github.com/gravitational/trace" | ||
"github.com/sirupsen/logrus" | ||
|
||
"github.com/gravitational/teleport/lib/backend" | ||
) | ||
|
||
// migrateIncorrectKeyTypes migrates incorrect key types (backend.Key and string) to the correct type (bytes) | ||
// in the backend. This is necessary because the backend was incorrectly storing keys as strings and backend.Key | ||
// types and Firestore clients mapped them to different database types. This forces calling ReadRange 3 times. | ||
// This migration will fix the issue by converting all keys to the correct type (bytes). | ||
// TODO(tigrato|rosstimothy): DELETE In 19.0.0: Remove this migration in 19.0.0. | ||
func (b *Backend) migrateIncorrectKeyTypes() { | ||
var ( | ||
numberOfDocsMigrated int | ||
duration time.Duration | ||
) | ||
err := backend.RunWhileLocked( | ||
b.clientContext, | ||
backend.RunWhileLockedConfig{ | ||
LockConfiguration: backend.LockConfiguration{ | ||
LockName: "firestore_migrate_incorrect_key_types", | ||
Backend: b, | ||
TTL: 5 * time.Minute, | ||
RetryInterval: time.Minute, | ||
}, | ||
ReleaseCtxTimeout: 10 * time.Second, | ||
RefreshLockInterval: time.Minute, | ||
}, | ||
func(ctx context.Context) error { | ||
start := time.Now() | ||
defer func() { | ||
duration = time.Since(start) | ||
}() | ||
// backend.Key is converted to array of ints when sending to the db. | ||
toArray := func(key []byte) []any { | ||
arrKey := make([]any, len(key)) | ||
for i, b := range key { | ||
arrKey[i] = int(b) | ||
} | ||
return arrKey | ||
} | ||
nDocs, err := migrateKeyType[[]any](ctx, b, toArray) | ||
numberOfDocsMigrated += nDocs | ||
if err != nil { | ||
return trace.Wrap(err, "failed to migrate backend key") | ||
} | ||
|
||
stringKey := func(key []byte) string { | ||
return string(key) | ||
} | ||
nDocs, err = migrateKeyType[string](ctx, b, stringKey) | ||
numberOfDocsMigrated += nDocs | ||
if err != nil { | ||
return trace.Wrap(err, "failed to migrate legacy key") | ||
} | ||
return nil | ||
}) | ||
|
||
entry := b.Entry.WithFields(logrus.Fields{ | ||
"duration": duration, | ||
"migrated": numberOfDocsMigrated, | ||
}) | ||
if err != nil { | ||
entry.WithError(err).Error("Failed to migrate incorrect key types.") | ||
return | ||
} | ||
entry.Infof("Migrated %d incorrect key types", numberOfDocsMigrated) | ||
} | ||
|
||
func migrateKeyType[T any](ctx context.Context, b *Backend, newKey func([]byte) T) (int, error) { | ||
limit := 300 | ||
startKey := newKey([]byte("/")) | ||
|
||
bulkWriter := b.svc.BulkWriter(b.clientContext) | ||
defer bulkWriter.End() | ||
|
||
nDocs := 0 | ||
// handle the migration in batches of 300 documents per second | ||
t := time.NewTimer(time.Second) | ||
defer t.Stop() | ||
for range t.C { | ||
tigrato marked this conversation as resolved.
Show resolved
Hide resolved
|
||
docs, err := b.svc.Collection(b.CollectionName). | ||
// passing the key type here forces the client to map the key to the underlying type | ||
// and return all the keys in that share the same underlying type. | ||
// backend.Key is mapped to Array in Firestore. | ||
// []byte is mapped to Bytes in Firestore. | ||
// string is mapped to String in Firestore. | ||
// Searching for keys with the same underlying type will return all keys with the same type. | ||
Where(keyDocProperty, ">", startKey). | ||
Limit(limit). | ||
Documents(ctx).GetAll() | ||
if err != nil { | ||
return nDocs, trace.Wrap(err) | ||
} | ||
|
||
jobs := make([]*firestore.BulkWriterJob, len(docs)) | ||
for i, dbDoc := range docs { | ||
newDoc, err := newRecordFromDoc(dbDoc) | ||
if err != nil { | ||
return nDocs, trace.Wrap(err, "failed to convert document") | ||
} | ||
|
||
// use conditional update to ensure that the document has not been updated since the read | ||
jobs[i], err = bulkWriter.Update( | ||
b.svc.Collection(b.CollectionName). | ||
Doc(b.keyToDocumentID(newDoc.Key)), | ||
newDoc.updates(), | ||
firestore.LastUpdateTime(dbDoc.UpdateTime), | ||
) | ||
if err != nil { | ||
return nDocs, trace.Wrap(err, "failed stream bulk action") | ||
} | ||
|
||
startKey = newKey(newDoc.Key) // update start key | ||
} | ||
|
||
bulkWriter.Flush() // flush the buffer | ||
|
||
for _, job := range jobs { | ||
if _, err := job.Results(); err != nil { | ||
// log the error and continue | ||
b.Entry.WithError(err).Error("failed to write bulk action") | ||
} | ||
} | ||
|
||
nDocs += len(docs) | ||
if len(docs) < limit { | ||
break | ||
} | ||
|
||
t.Reset(time.Second) | ||
} | ||
return nDocs, nil | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably worth using a
FullJitter
on this delay to ensure that it still eventually gets run even if auth is being frequently restarted. That will mean that some small portion of the time it'll interfere a bit with startup, but IMO it's worth it in order to be confident that it'll eventually get run in the context of frequent restarts.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Switched to interval.