Skip to content
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

VReplication: Properly support cancel and delete for multi-tenant MoveTables #16906

Merged
merged 34 commits into from
Oct 23, 2024

Conversation

mattlord
Copy link
Contributor

@mattlord mattlord commented Oct 7, 2024

Description

This PR fixes #16919 by taking a different execution path when cleaning up a multi-tenant MoveTables workflow (one created with the --tenant-id flag):

  1. Instead of dropping the target tables, we delete only the given tenant's rows in the target tables
    • This is done in batches — the default size of 1,000 can be changed via the new --delete-batch-size flag for cancel — to prevent performance issues on the target keyspace (the target is most likely serving production traffic from this table for already migrated tenants)
    • We consult the tablet throttler to be sure that we're not having too large of an impact on the production system while this cleanup work is happening
    • We do not delete the workflow itself until after all of the data has been cleaned up as we may not be able to remove all of it before the command times out
  2. We do not try and clean up global resources such as denied table entries and routing rules as those are not applicable with multi-tenant migrations

⚠️ The batched deleting of the data that had been migrated in the multi-tenant workflow can take a long time. The default timeout for that work is 1 hour, controlled via the vtctldclient --action_timeout flag. If the work cannot complete before the command times out, then you will need to run the command again to continue cleaning it up from where we left off.

Manual test

cd examples/local

./101_initial_cluster.sh; mysql < ../common/insert_commerce_data.sql; ./201_customer_tablets.sh

alias vtctldclient='command vtctldclient --server=localhost:15999'

mysql -e "alter table customer add tenant_id int unsigned"

echo -e "\nSetting up multi-tenant-spec in vschema...\n"
vtctldclient ApplyVSchema --vschema='{
  "sharded": false,
  "vindexes": {},
  "tables": {},
  "require_explicit_routing": false,
  "foreign_key_mode": "unspecified",
  "multi_tenant_spec": {"tenant_id_column_name": "tenant_id","tenant_id_column_type": "INT64"}
}' customer

echo -e "\nGenerating test data for tenant-id 99...\n"
for i in {1..1000}; do
  mysql commerce -e "insert into customer (email, tenant_id) values ('mlord_${i}_${RANDOM}@planetscale.com', 99)"
done

echo -e "\nGenerating test data for tenant-id 100...\n"
for i in {1..1000}; do
  mysql commerce -e "insert into customer (email, tenant_id) values ('mlord_${i}_${RANDOM}@planetscale.com', 100)"
done

echo -e "\nCreating workflow for tenant-id 99...\n"
vtctldclient MoveTables --workflow commerce2customer_99 --target-keyspace customer create --source-keyspace commerce --tables customer --tenant-id=99

echo -e "\nCreating workflow for tenant-id 100...\n"
vtctldclient MoveTables --workflow commerce2customer_100 --target-keyspace customer create --source-keyspace commerce --tables customer --tenant-id=100

sleep 10

echo -e "\nCancelling workflow for tenant-id 99...\n"
vtctldclient --action_timeout 100ms MoveTables --workflow commerce2customer_99 --target-keyspace customer cancel --delete-batch-size=1

echo -e "\nRows left in table after timed out cancelation...\n"
mysql customer/0 -e "select count(*) from customer"

echo -e "\nCancelling workflow for tenant-id 99 again...\n"
vtctldclient --action_timeout 5m MoveTables --workflow commerce2customer_99 --target-keyspace customer cancel --delete-batch-size=1

echo -e "\nRows left in table after cancelation...\n"
mysql customer/0 -e "select count(*) from customer"

Results on this PR branch:

...
Cancelling workflow for tenant-id 99...

E1010 10:48:43.545834   80224 main.go:56] Cancel action timed out. Please try again and the work will pick back up where it left off. Note that you can control the timeout using the --action_timeout flag and the delete batch size with --delete-batch-size.

Rows left in table after timed out cancelation...

+----------+
| count(*) |
+----------+
|     1818 |
+----------+

Cancelling workflow for tenant-id 99 again...

Successfully cancelled the commerce2customer_99 workflow in the customer keyspace


Rows left in table after cancelation...

+----------+
| count(*) |
+----------+
|     1000 |
+----------+

Related Issue(s)

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation: Document changes from https://github.com/vitessio/vitess/pull/16906 website#1866

Signed-off-by: Matt Lord <mattalord@gmail.com>
@mattlord mattlord added Type: Enhancement Logical improvement (somewhere between a bug and feature) Component: VReplication labels Oct 7, 2024
Copy link
Contributor

vitess-bot bot commented Oct 7, 2024

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@vitess-bot vitess-bot bot added NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says labels Oct 7, 2024
@mattlord mattlord marked this pull request as draft October 7, 2024 15:53
@mattlord mattlord removed the request for review from ajm188 October 7, 2024 15:53
@mattlord mattlord removed the NeedsBackportReason If backport labels have been applied to a PR, a justification is required label Oct 7, 2024
@github-actions github-actions bot added this to the v21.0.0 milestone Oct 7, 2024
Copy link

codecov bot commented Oct 7, 2024

Codecov Report

Attention: Patch coverage is 61.76471% with 91 lines in your changes missing coverage. Please review.

Project coverage is 67.16%. Comparing base (c429d51) to head (87d4f68).
Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
go/vt/vtctl/workflow/server.go 69.29% 35 Missing ⚠️
go/vt/vttablet/tabletmanager/rpc_vreplication.go 69.33% 23 Missing ⚠️
go/vt/vttablet/grpctmclient/client.go 0.00% 11 Missing ⚠️
go/vt/vtctl/workflow/traffic_switcher.go 70.58% 5 Missing ⚠️
go/vt/vttablet/grpctmserver/server.go 0.00% 5 Missing ⚠️
...vtctldclient/command/vreplication/common/cancel.go 0.00% 4 Missing ⚠️
go/vt/vttablet/tmrpctest/test_tm_rpc.go 0.00% 3 Missing ⚠️
go/vt/vtcombo/tablet_map.go 0.00% 2 Missing ⚠️
go/vt/vttablet/faketmclient/fake_client.go 0.00% 2 Missing ⚠️
...ctldclient/command/vreplication/workflow/delete.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16906      +/-   ##
==========================================
+ Coverage   67.13%   67.16%   +0.02%     
==========================================
  Files        1571     1571              
  Lines      251868   252060     +192     
==========================================
+ Hits       169091   169284     +193     
+ Misses      82777    82776       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Signed-off-by: Matt Lord <mattalord@gmail.com>
@mattlord mattlord force-pushed the multi_tenant_movetables_cleanup branch from c59e117 to 435ff92 Compare October 7, 2024 16:40
Signed-off-by: Matt Lord <mattalord@gmail.com>
@mattlord mattlord force-pushed the multi_tenant_movetables_cleanup branch 6 times, most recently from 399cb1f to ab22f0d Compare October 7, 2024 20:54
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
@mattlord mattlord force-pushed the multi_tenant_movetables_cleanup branch from ab22f0d to 68d28b9 Compare October 7, 2024 21:32
@mattlord mattlord removed the request for review from frouioui October 10, 2024 00:53
Signed-off-by: Matt Lord <mattalord@gmail.com>
go/vt/vtctl/workflow/server.go Outdated Show resolved Hide resolved
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
1. Stop the workflow so that it doesn't do anymore work
2. Delete the related artifacts
3. Delete the workflow itself

This allows for repeated cancel/delete attempts if the
cleanup work fails to complete succesfully.

Signed-off-by: Matt Lord <mattalord@gmail.com>
…es_cleanup

Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
mattlord added a commit to vitessio/website that referenced this pull request Oct 16, 2024
Signed-off-by: Matt Lord <mattalord@gmail.com>
@mattlord mattlord removed the NeedsWebsiteDocsUpdate What it says label Oct 16, 2024
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
@mattlord mattlord requested a review from deepthi October 16, 2024 04:05
Copy link
Member

@deepthi deepthi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work! I do think it's important for flag help to be consistent. I can approve once that is fixed.

@@ -60,6 +61,7 @@ func registerCommands(root *cobra.Command) {
delete.MarkFlagRequired("workflow")
delete.Flags().BoolVar(&deleteOptions.KeepData, "keep-data", false, "Keep the partially copied table data from the workflow in the target keyspace.")
delete.Flags().BoolVar(&deleteOptions.KeepRoutingRules, "keep-routing-rules", false, "Keep the routing rules created for the workflow.")
delete.Flags().Int64Var(&deleteOptions.DeleteBatchSize, "delete-batch-size", movetables.DefaultDeleteBatchSize, "The batch size to use when deleting a subset of data from the migrated tables. This is only used with multi-tenant MoveTables workflows.")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this description not be consistent with that given for the same flag in moveables.go for the Cancel sub-command?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch! However, this is a bit of an exception in that the context is different for MoveTables cancel and Workflow delete. It was intentional:

go/cmd/vtctldclient/command/vreplication/movetables/movetables.go:      cancel.Flags().Int64Var(&common.CancelOptions.DeleteBatchSize, "delete-batch-size", DefaultDeleteBatchSize, "When cleaning up the migrated data in tables moved as part of a mult-tenant workflow, delete the records in batches of this size.")
go/cmd/vtctldclient/command/vreplication/workflow/workflow.go:  delete.Flags().Int64Var(&deleteOptions.DeleteBatchSize, "delete-batch-size", movetables.DefaultDeleteBatchSize, "The batch size to use when deleting a subset of data from the migrated tables. This is only used with multi-tenant MoveTables workflows.")

But I'm good tweaking them if you have any suggestions or preference?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand how they are different. As long as they are both consistent, either way of wording the flag help is fine.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On second thought, this is somewhat misleading

The batch size to use when deleting a subset of data from the migrated tables

It makes it sound as if there's some general capability to delete a subset of data from migrated tables. So the other version is preferable.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need them to be exactly the same? That would be a little odd as MoveTables cancel is obviously for MoveTables. What about:

go/cmd/vtctldclient/command/vreplication/movetables/movetables.go:      cancel.Flags().Int64Var(&common.CancelOptions.DeleteBatchSize, "delete-batch-size", DefaultDeleteBatchSize, "When cleaning up the migrated data in tables moved as part of a multi-tenant workflow, delete the records in batches of this size.")
go/cmd/vtctldclient/command/vreplication/workflow/workflow.go:  delete.Flags().Int64Var(&deleteOptions.DeleteBatchSize, "delete-batch-size", movetables.DefaultDeleteBatchSize, "When cleaning up the migrated data in tables moved as part of a multi-tenant MoveTables workflow, delete the records in batches of this size.")

The only difference being we note that it's for a multi-tenant MoveTables workflow in the Workflow delete help output.

And I just realized a misspelling in there mult-tenant that I corrected above. :)

…es_cleanup

Signed-off-by: Matt Lord <mattalord@gmail.com>
Comment on lines -2149 to -2151
if len(res) == 0 {
return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "the %s workflow does not exist in the %s keyspace", req.Workflow, req.Keyspace)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this check no longer necessary? Or was it redundant in the first place?

Copy link
Contributor Author

@mattlord mattlord Oct 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We now delete the actual workflow at the end, and by this time we've already read the workflow details. Followed by cleaning up all related artifacts. And we now hold the workflow lock throughout all of it. So at this point if the workflow itself is gone that's not an error condition.

Comment on lines +1724 to +1732
// Lock the workflow while we complete it.
lockName := fmt.Sprintf("%s/%s", ts.TargetKeyspaceName(), ts.WorkflowName())
ctx, workflowUnlock, lockErr := s.ts.LockName(ctx, lockName, "MoveTablesComplete")
if lockErr != nil {
ts.Logger().Errorf("Locking the workflow %s failed: %v", lockName, lockErr)
return nil, vterrors.Wrapf(lockErr, "failed to lock the %s workflow", lockName)
}
defer workflowUnlock(&err)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The locking code seems to have been moved. Is there a consistent rule that we now follow for where we lock? We seem to call each lower level function (dropSources / DropTargets / DeleteTenantData) only in one place, so in practice we acquire/release the lock once regardless of where we do it.

Copy link
Contributor Author

@mattlord mattlord Oct 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The keyspace locks were not moved. The workflow locks were moved so that the workflow is locked while the larger operation is happening. For example we hold it throughout the WorkflowDelete operation, which ends with deleting the workflow (and us releasing the workflow lock at the end). The keyspace locks we take only when needed and release ASAP as there's contention for those (e.g. schema changes). Remember that the workflow locks are pretty new. When I initially added them I added them in the same spot we took the keyspace locks. But on further thought, it makes sense to hold them longer. That became clear when I moved the workflow deletion to AFTER we cleanup the other related artifacts and data (where the workflow lock was previously taken and released).

go/vt/vtctl/workflow/server.go Outdated Show resolved Hide resolved
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
Signed-off-by: Matt Lord <mattalord@gmail.com>
@deepthi deepthi merged commit 17607fa into vitessio:main Oct 23, 2024
101 checks passed
@deepthi deepthi deleted the multi_tenant_movetables_cleanup branch October 23, 2024 06:13
deepthi pushed a commit to vitessio/website that referenced this pull request Oct 24, 2024
* Document changes from vitessio/vitess#16906

Signed-off-by: Matt Lord <mattalord@gmail.com>

* Bring v22 docs up-to-date with main after PR merged

Signed-off-by: Matt Lord <mattalord@gmail.com>

* Add two new files

Signed-off-by: Matt Lord <mattalord@gmail.com>

* Update v21 docs as well

Signed-off-by: Matt Lord <mattalord@gmail.com>

---------

Signed-off-by: Matt Lord <mattalord@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: VReplication Type: Enhancement Logical improvement (somewhere between a bug and feature)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature Request: Properly support MoveTables cancel for multi-tenant migrations
4 participants