Skip to content

[full-ci] feat: fix the graceful shutdown using the new ocis and reva runners - #11295

Merged
2403905 merged 7 commits into
owncloud:masterfrom
2403905:issue-11170
May 28, 2025
Merged

2403905 merged 7 commits into
owncloud:masterfrom
2403905:issue-11170

Conversation

@2403905

@2403905 2403905 commented May 7, 2025 •

Copy link
Copy Markdown
Contributor

Description

#9048

Related Issue

Motivation and Context

How Has This Been Tested?

  • test environment:
  • test case 1:
  • test case 2:
  • ...

Screenshots (if appropriate):

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Technical debt
  • Tests only (no source changes)

Checklist:

  • Code changes
  • Unit tests added
  • Acceptance tests added
  • Documentation ticket raised:

@2403905
2403905 requested a review from kobergj May 7, 2025 16:26
@jvillafanez

Copy link
Copy Markdown
Member

I think we need to align the solution with #9048 .

My expectation is that we create a NewRevaServiceRunner in the "ocis-pkg/runner/factory.go" file following the same approach of #9048 . That should work fine at least for isolated services.
There are different timeouts for group runners and individual runners so we adjust the values to give enough time to the reva services to shutdown properly. Once the timeout is reached (or the service finishes), the main thread is expected to keep going, eventually reaching the end of the program, forcing the shutdown of the whole app. It should be impossible to have the application stuck indefinitely after being asked to shutdown.

For isolated processes, the basic idea is that you start a group runner which will hold individual runners, one for the http service, another for the grpc service and another for the debug server (all of them if applicable). The group runner will ensure that each individual runner in the group stops if ANY individual runner stops (basically either all services in the group are running or none of them are)

For the "all-in-one" / supervisor process, we'll need to think about it:

  • With [WIP] feat: use runners to startup the services #9048 , the services are configured to stop after receiving the sigquit / sigterm signals, so the supervisor shouldn't need to handle those.
  • Finishing the context will also be used to signal the services to stop.
  • I expect the services to be shutdown randomly without any particular order. If this is a requirement, there could be workarounds that we might implement, but we'll need to handle signals differently.

My worry is that I think we have to deregister all the services from the supervisor first before starting to shutdown the services, otherwise the supervisor might restart the service.

Comment thread ocis/pkg/runtime/service/service.go Resolved
@2403905

2403905 commented May 8, 2025

Copy link
Copy Markdown
Contributor Author

I think we could add a generic function NewRevaServiceRunner, but for this purpose, we should rewrite the reva runtime to handle the context-based interruption signal from the outside. The reason why reva uses its own signal channel is that reva handles the hot-reload signal that is anyway handled by ocis as a stop signal.

The timeouts should be configurable but at the same time, should have a reasonable default value that should be based on the Kubernetes service stop timeouts, in my vision.

@2403905
2403905 requested a review from jvillafanez May 12, 2025 21:30
@2403905 2403905 changed the title Fix the graceful shutdown feat: fix the graceful shutdown using the new ocis and reva runners May 13, 2025
@2403905 2403905 changed the title feat: fix the graceful shutdown using the new ocis and reva runners [full-ci] feat: fix the graceful shutdown using the new ocis and reva runners May 13, 2025
@2403905
2403905 force-pushed the issue-11170 branch 2 times, most recently from 9349fc8 to 23dbd39 Compare May 13, 2025 14:29
@2403905
2403905 force-pushed the issue-11170 branch 2 times, most recently from b7e8539 to a33260c Compare May 21, 2025 16:16
Comment thread ocis/pkg/runtime/service/service.go Resolved
@2403905
2403905 force-pushed the issue-11170 branch 4 times, most recently from 84bc904 to 3eafff1 Compare May 26, 2025 12:16
@2403905
2403905 marked this pull request as ready for review May 26, 2025 12:20
@2403905
2403905 requested a review from LukasHirt as a code owner May 26, 2025 12:20
@2403905
2403905 requested a review from Copilot May 26, 2025 12:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes the graceful shutdown behavior by migrating from the legacy run.Group to the new ocis and reva runners. Key changes include replacing oklog/run with runner.NewGroup in multiple service commands, updating cancellation contexts via os/signal.NotifyContext, and enhancing shutdown logic in both service and runtime components.

Reviewed Changes

Copilot reviewed 62 out of 62 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
services/collaboration/pkg/command/server.go Migrated to new runner and updated context cancellation and GRPC/HTTP server runners.
services/clientlog/pkg/service/service.go Introduced stop channels and atomic flags to control event loop termination.
services/*/pkg/command/server.go Multiple auth and app services now rely on runner.NewGroup and new runner runners for improved shutdown handling.
services/audit/pkg/{service,command}/... Added checks for channel closure and context errors in audit logging.
services/antivirus/pkg/{service,command}/... Updated antivirus service to use graceful shutdown via new stop channels and atomic.Bool; fixed server runner usage.
ocis/pkg/runtime/service/service.go Revised runtime shutdown logic to asynchronously remove supervised services and wait for graceful termination.
ocis-pkg/runner/* Updated default interrupt durations and introduced New*Runner functions for GRPC, HTTP, and reva services.
go.mod Updated dependency version for github.com/owncloud/reva/v2.
Comments suppressed due to low confidence (1)

services/collaboration/pkg/command/server.go:132

  • [nitpick] The log level was changed from error to info for reporting initialization failures; verify if this adjustment is intentional, as error conditions should typically be logged at the error level.
logger.Info().Err(err).Str("transport", "http").Msg("Failed to initialize server")

// Since Shutdown might take some time, don't block
go func() {
// TODO: Provide the adjustable TimeoutDuration
shutdownCtx, cancel := context.WithTimeout(context.Background(), DefaultInterruptDuration)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

For the timeout, we can provide an additional parameter:

func NewGolangHttpServerRunner(name string, server *http.Server, shutdownTimeout time.Duration, opts ...Option) *Runner { .... }

It's part of what the "interrupt" function needs to do, the same way as the name and the server, so it's fine to add another parameter just for this function. Consider it as a requirement to setup the function that needs to be run.
Using opts in this case is wrong because opts are being used to control the behavior of the runner, independently of whatever the runner is executing.

In addition, we probably should move the DefaultTimeoutDuration constant here. Constants in the "option.go" file should refer to the runner's options, but this constant refers to this particular function.
I'd prefer hardcoding the value in this case, but since the caller will need to provide a value, it makes sense for us to offer a default value as a constant. We can use the default value as a minimum value.

We need to clarify that the shutdownTimeout will be used to wait for the server to stop, but the runner WON'T wait for it if the value is lower than the runner's interrupt duration.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

For the timeout, we can provide an additional parameter:

We need to clarify that the shutdownTimeout will be used to wait for the server to stop, but the runner WON'T wait for it if the value is lower than the runner's interrupt duration.

Does it even make sense to have so many adjustments? Let's keep it simple for now.
Why I think the timeouts DefaultInterruptDuration = 20 * time.Secondand DefaultGroupInterruptDuration = 25 * time.Second reasonably enough:
The Kubernetes terminates with the default grace period 30 seconds
After the TERM signal is committed the GroupRunner lets each individual task Runner try
to stop gracefully in DefaultInterruptDuration seconds and after DefaultGroupInterruptDuration seconds stops the group.

In addition, we probably should move the DefaultTimeoutDuration constant here. Constants in the "option.go" file should refer to the runner's options, but this constant refers to this particular function.
I'd prefer hardcoding the value in this case, but since the caller will need to provide a value, it makes sense for us to offer a default value as a constant. We can use the default value as a minimum value.

We could reorganize the code. We shouldn't provide new options because they bring more complexity that doesn't provide any advantage to me.
I see the point of using these constants in the trapShutdownCtx() since they are related to theGroupRunner
https://github.com/owncloud/ocis/pull/11295/files#diff-0592eab66ff0d2d4d945791b45713db11c276a28ceb3cd69e72594c3e2ad45e6R512-R554

@2403905
2403905 requested review from jvillafanez and removed request for LukasHirt May 27, 2025 07:34
}()

// trapShutdownCtx will block on the context-done channel for interruptions.
trapShutdownCtx(s, srv, ctx)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm having doubts with this... I think the only way to close the app properly is by finishing the context, which, assuming everything is correctly set up, can be done through an OS signal. However, if we can't start the server, are we stuck?

In addition, I miss the point of the srv := new(http.Server) (or the old http.Serve(l, nil)). I don't think we're serving anything, so it seems we're just using it to wait for something and block the thread. If this is the case, there should be easier and less resource-intensive to achieve the goal.

So, what do we need the server for?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm having doubts with this... I think the only way to close the app properly is by finishing the context, which, assuming everything is correctly set up, can be done through an OS signal. However, if we can't start the server, are we stuck?

Good question. I'll check.

In addition, I miss the point of the srv := new(http.Server) (or the old http.Serve(l, nil)). I don't think we're serving anything, so it seems we're just using it to wait for something and block the thread. If this is the case, there should be easier and less resource-intensive to achieve the goal.
So, what do we need the server for?

It is used for a recovery check. I don't know what an idea is exactly. But maybe we should not stop it gracefully, just let it die

	defer func() {
		if r := recover(); r != nil {
			reason := strings.Builder{}
			if _, err = net.Dial("tcp", net.JoinHostPort(s.cfg.Runtime.Host, s.cfg.Runtime.Port)); err != nil {
				reason.WriteString("runtime address already in use")
			}

			fmt.Println(reason.String())
		}
	}()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe @kobergj knows the reason for that code. Meanwhile I'd vote for removing this.

Panics should never happen. If they happen, we must get as much information as possible to fix them immediately.
As far as I know, if a panic happen, that code will hide the panic and MAYBE show a "runtime address already in use" message, which seems useless to me in that scenario. The app will end up finishing the same way as with a panic, but without a panic message.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I talked to @kobergj. The http.Server here is a built-in RPC server that serves func (s *Service) List(_ struct{}, reply *string) error calls from the cli command ocis list
The recover doesn't make sense. We decided to remove.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I wrapped the RPC in a func (s *Service) runRPCServer(). The graceful shutdown is redundant in this case to me.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm having doubts with this... I think the only way to close the app properly is by finishing the context, which, assuming everything is correctly set up, can be done through an OS signal. However, if we can't start the server, are we stuck?

The server finishes with code 1 if it can't start. I replaced the os.Exit()with thes.log.Fatal()` calls.
Or calls the context cancel() function if the supervisor has reached the failure threshold.

@jvillafanez jvillafanez May 28, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The http.Server here is a built-in RPC server that serves func (s *Service) List(_ struct{}, reply *string) error calls from the cli command ocis list

I'll open a ticket to handle it better. Using a hidden default var in a external package to link the rpc setup with the server that will handle the connections seems a bad idea. I know that's how the example in the documentation does it, but I'd prefer to be more explicit.

(#11376)

@2403905
2403905 force-pushed the issue-11170 branch 2 times, most recently from c4e4ab6 to dd184e2 Compare May 28, 2025 07:36
@jvillafanez

Copy link
Copy Markdown
Member

Code looks fine to me. #11376 can be postponed for now because the PR is already too big. Other than that I think we're good to go after fixing the CI.

@jvillafanez

Copy link
Copy Markdown
Member

Linking with #11377 to track the panic error. As said, the PR is already big and fixing it will take some time (we need to ensure the service is thread-safe), so we'll handle it later in a different PR.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
54.6% Duplication on New Code (required ≤ 50%)

See analysis details on SonarQube Cloud

@2403905
2403905 merged commit 1148dcc into owncloud:master May 28, 2025
ownclouders pushed a commit that referenced this pull request May 28, 2025
[full-ci] feat: fix the graceful shutdown using the new ocis and reva runners
@jvillafanez

Copy link
Copy Markdown
Member

@2403905 could you add some logs? I think we need to know when the service starts, when it receives the stop signal (or when the service notices it) and when the service stops.

I don't think this is working correctly in my environment. Most of the containers stops after 1 or 2 seconds, including the ocis' wopi server (the isolated collaboration server), however, the ocis server always hits the docker compose timeout. It also hits the timeout after increasing it to 30 secs.

The system is pretty much idle, just start and stop after one or two minutes without even login any user. Definitely it shouldn't take more than 30 secs to finish cleanly.

@2403905

2403905 commented Jun 5, 2025

Copy link
Copy Markdown
Contributor Author

@jvillafanez Is it the proper place for each individual service?

			grResults := gr.Run(cfg.Context)

			logger.Warn().Msgf("the %s service is shuting down", cfg.Service.Name)
			// return the first non-nil error found in the results
			for _, grResult := range grResults {
				if grResult.RunnerError != nil {
					return grResult.RunnerError
				}
			}
			logger.Warn().Msgf("the %s service is stopped without error", cfg.Service.Name)

@jvillafanez

Copy link
Copy Markdown
Member

If there is no better option, yes, that could be a good place.

@jvillafanez

Copy link
Copy Markdown
Member

I don't think this is working correctly in my environment. Most of the containers stops after 1 or 2 seconds, including the ocis' wopi server (the isolated collaboration server), however, the ocis server always hits the docker compose timeout. It also hits the timeout after increasing it to 30 secs.

This is a problem with the deployment, not with the code. Basically, the deployment example runs a shell with executes ocis; docker will deliver the SIGTERM signal to the shell, but the shell won't forward the signal to oCIS, so the oCIS won't will never finish.
The other oCIS-related container runs the oCIS service directly so they don't have this problem.

I'll open a ticket to check how we can handle the problem in the deployment example, but as said, the code seems to work fine (I haven't checked in depth, but at least the container stops)

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.

Proxy Service not shutting down gracefully

3 participants