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

Gracefully finishing deferred calls #792

Merged
merged 1 commit into from
Dec 9, 2021
Merged

Conversation

kuritka
Copy link
Collaborator

@kuritka kuritka commented Dec 9, 2021

We recently solved how to exit k8gb and make sure all deferred calls are done. The solution was to run a defer at the very end of the program, which decided whether to run os.Exit(0) or os.Exit(1).

Although this solution works, it is still somewhat difficult to understand and quite error prone from the point of view that from the very start of the program, we have to maintain the state of how the program exits.

The following refactoring uses a different pattern - which is stateless and maight be potentionally accepted by the kubebuilder when the PR is created.

package main

func main() {
	if err := run(); err != nil {
		os.Exit(1)
	}
}

func run() error {

	// Current main() code with logs <-- logging, initializing etc.. is here

	return nil
}

Signed-off-by: kuritka kuritka@gmail.com

We recently solved how to exit k8gb and make sure all deferred calls are done. The solution was to run a defer at the very end of the program, which decided whether to run os.Exit(0) or os.Exit(1).

Although this solution works, it is still somewhat difficult to understand and quite error prone from the point of view that from the very start of the program, we have to maintain the state of how the program exits.

The following refactoring uses a different pattern - which is stateless and will be accepted by the kubebuilder when the PR is created.

```go
package main

func main() {
	if err := run(); err != nil {
		os.Exit(1)
	}
}

func run() error {

	// Current main() code with logs <-- logging, initializing etc.. is here

	return nil
}

```

Signed-off-by: kuritka <kuritka@gmail.com>
Copy link
Member

@ytsarev ytsarev left a comment

Choose a reason for hiding this comment

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

Looks very clean 👍

@kuritka kuritka merged commit 1df2e71 into master Dec 9, 2021
@kuritka kuritka deleted the gracefully-finished-v2 branch December 9, 2021 15:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants