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

go/cmd: Audit and fix context.Background() usage #15928

Merged
merged 2 commits into from May 15, 2024

Conversation

dbussink
Copy link
Contributor

This removes a bunch of the context.Background() usage for the command line entrypoints. In general, we should use the command context (which normally is context.Background(), but it's more semantically accurate).

There's a few cases where we need more fixes. Specifically in vtgate where we want to setup a cancellable context and cancel it when we shut down. This is the one that ends up running things like the topo watcher and this ensures things are closed appropriately.

Similarly in vtcombo we apply similar fixes so that we always correctly cancel the context on shutdown and the same for vttablet.

Related Issue(s)

Fixes #15927

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 was added or is not required

Copy link
Contributor

vitess-bot bot commented May 13, 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 May 13, 2024
@github-actions github-actions bot added this to the v20.0.0 milestone May 13, 2024
@@ -189,17 +189,20 @@ func run(cmd *cobra.Command, args []string) (err error) {
cmd.Flags().Set("log_dir", "$VTDATAROOT/tmp")
}

ctx, cancel := context.WithCancel(cmd.Context())
defer cancel()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This creates the toplevel context here and then uses it for example for creating the memory topo and other operations too.

Once this cancels, it ensures that things like the topo and watchers etc. are closed in the right order.

}

servenv.OnRun(func() {
addStatusParts(vtg)
})

servenv.OnTerm(func() {
log.Error("Terminating")
// FIXME(alainjobart): stop vtgate
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is actually fixed now that the context is cancelled that is used to setup vtgate, so we can remove the TODO and the whole block here as it does nothing.

// We will still use the topo server during lameduck period
// to update our state, so closing it in OnClose()
ts.Close()
})
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Closing the topo isn't a long running operation or anything, so we can do it with a defer when we create it, removing the need for this callback to be used here at all.

It doesn't change the order of things, since right after RunDefault below we return, and then we'd run the defer now to close ts as well.

resilientServer = srvtopo.NewResilientServer(context.Background(), ts, srvTopoCounts)
ctx, cancel := context.WithCancel(cmd.Context())
defer cancel()
resilientServer = srvtopo.NewResilientServer(ctx, ts, srvTopoCounts)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This fix ensures that during shutdown we don't hit the panic from #15927, because the context will have been cancelled always before the topo is closed (which is deferred right above here).

defer ts.Close()

ctx, cancel := context.WithCancel(cmd.Context())
defer cancel()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This logic is moved here to match how vtgate is set up, so we open and defer close / cancel in the right order.

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you also add a comment in the code to this effect as well? That will help to ensure that this implied behavior is not changed later by someone not fully realizing the important of the order here.

@@ -170,9 +175,6 @@ func run(cmd *cobra.Command, args []string) error {
// Close the tm so that our topo entry gets pruned properly and any
// background goroutines that use the topo connection are stopped.
tm.Close()

// tm uses ts. So, it should be closed after tm.
ts.Close()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

We handle this with the above defer, so no need to close it here.

@dbussink dbussink removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels May 13, 2024
@dbussink dbussink force-pushed the dbussink/fix-cmd-context-setup branch from fbf3970 to 42b4588 Compare May 13, 2024 12:41
Copy link

codecov bot commented May 13, 2024

Codecov Report

Attention: Patch coverage is 1.56250% with 63 lines in your changes are missing coverage. Please review.

Project coverage is 68.46%. Comparing base (473c49a) to head (cf32fe9).
Report is 1 commits behind head on main.

Files Patch % Lines
go/cmd/vtcombo/cli/main.go 0.00% 22 Missing ⚠️
go/cmd/vtcombo/cli/vschema_watcher.go 0.00% 7 Missing ⚠️
go/cmd/vtgate/cli/cli.go 0.00% 6 Missing ⚠️
go/cmd/vttablet/cli/cli.go 0.00% 6 Missing ⚠️
go/cmd/vtbackup/cli/vtbackup.go 0.00% 5 Missing ⚠️
go/cmd/vtctldclient/command/legacy_shim.go 0.00% 3 Missing ⚠️
go/cmd/mysqlctld/cli/mysqlctld.go 0.00% 2 Missing ⚠️
go/cmd/vtexplain/cli/vtexplain.go 0.00% 2 Missing ⚠️
go/cmd/mysqlctl/command/init.go 0.00% 1 Missing ⚠️
go/cmd/mysqlctl/command/shutdown.go 0.00% 1 Missing ⚠️
... and 8 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15928      +/-   ##
==========================================
+ Coverage   68.45%   68.46%   +0.01%     
==========================================
  Files        1559     1559              
  Lines      196872   196871       -1     
==========================================
+ Hits       134769   134789      +20     
+ Misses      62103    62082      -21     

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

Copy link
Contributor

@mattlord mattlord left a comment

Choose a reason for hiding this comment

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

This is a nice piece of cleanup! Thank you ❤️

defer ts.Close()

ctx, cancel := context.WithCancel(cmd.Context())
defer cancel()
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you also add a comment in the code to this effect as well? That will help to ensure that this implied behavior is not changed later by someone not fully realizing the important of the order here.

This removes a bunch of the context.Background() usage for the command
line entrypoints. In general, we should use the command context (which
normally is context.Background(), but it's more semantically accurate).

There's a few cases where we need more fixes. Specifically in vtgate
where we want to setup a cancellable context and cancel it when we shut
down. This is the one that ends up running things like the topo watcher
and this ensures things are closed appropriately.

Similarly in vtcombo we apply similar fixes so that we always correctly
cancel the context on shutdown and the same for vttablet.

Signed-off-by: Dirkjan Bussink <d.bussink@gmail.com>
Signed-off-by: Dirkjan Bussink <d.bussink@gmail.com>
@dbussink dbussink force-pushed the dbussink/fix-cmd-context-setup branch from 42b4588 to cf32fe9 Compare May 14, 2024 12:01
Copy link
Member

@frouioui frouioui left a comment

Choose a reason for hiding this comment

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

This is really nice

Copy link
Member

@GuptaManan100 GuptaManan100 left a comment

Choose a reason for hiding this comment

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

LGTM!

@dbussink dbussink merged commit 61061cb into vitessio:main May 15, 2024
93 checks passed
@dbussink dbussink deleted the dbussink/fix-cmd-context-setup branch May 15, 2024 05:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug Report: vtgate can crash on shutdown
4 participants