Implement graceful shutdown
The current shutdown sequence in Mesos is to send a TERM, followed by a KILL 3 seconds later if the process is still running. Some apps have more advanced requirements like deregistering from a load balancer before shutting down. This thread is to collect requirements for a graceful shutdown feature.
There is a patch in flight that makes the timeout configurable: https://reviews.apache.org/r/25434/
Signals and few seconds are not easy to manage. For TCP based services, there may not be a better option but I don't know how this would work for docker tasks. For HTTP services, my suggestion would be to add an option, just like the health check, to leverage a shutdown URI. That way the application can take the necessary time to drain and possibly stop responding to health checks.
I linked a ticket from the bamboo haproxy project. It looks like we probably also need some kind of "draining" state of a task with corresponding status events, in order to make bamboo and similar projects behave well on shutdown of tasks.
@sttts that's a nice clean way to handle it.
It would be cool if there will be configurable pre-killing task like: reach instance:port/kill URL before killing - so we can implement better logic in instance application (for example we will mark self health checks as unhealthy -> it would get out from HAproxy) and of course this configurable timeout will be also needed.
#1147 was a duplicate, copying some ideas:
Apps that are super-fast to deploy (like golang apps in docker containers on top of busybox image that are already downloaded) can result in state when all old tasks are killed, but no new tasks are present in service discovery because update didn't happen yet.
I think we could ease transition to mesos/marathon with some timeout for tasks when they are not exposed in marathon api for service discovery, but still running.
Hiding from api or marking as unhealthy before killing with configurable timeout would improve things a lot for apps with connect-request-response-disconnect apps (think php).
Clever apps can catch signals and do draining shutdown, with configurable timeout between SIGTERM and SIGKILL per app that should work pretty well.
Ideally I would like something like this:
Marathon asks instances to stop themselves by sending a rest request (PUT to the shutdown path). The response is could be 200 OK, or 202 Accepted for instances willing to shutdown, or 409 Conflict to indicate that instance would prefer not to shutdown. If marathon really, really wants the instance to stop it sends a DELETE to the shutdown path. This one must be obeyed. Alternatives are a command or TCP, just like health checking.
Marathon would use the configured timeout to ensure the task actually died out. If it did not die within the timeout, then it is killed off using mesos as happens now.
If not enough instances respond with 200 OK or 202 Accepted, then marathon could retry through the task set for a configurable amount of time, and finally, if there are still more to stop, use the DELETE to make it unconditional.
This kind of process would allow instances to drain any current workload and stop themselves in an orderly fashion. Not only that, some instances doing important work could effectively say "pick someone else please".
You could do it without the option for declining a shutdown. In effect, you are going to make shutdown mandatory, and wait a configured amount of time for it to happen in an orderly fashion, and after that timeout just follow the current procedure. But having the option to decline a shutdown allows you to find idle instances of services. An idle service can shutdown immediately with no consequences.
CC @BenWhitehead and @jsancio
As @bobrik said, I would stick with POSIX signals. Sending SIGTERM is a standard way to do this http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals
The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process. This allows the process to perform nice termination releasing resources and saving state if appropriate.
Applications controlled by other tools like http://supervisord.org/configuration.html#program-x-section-settings expects it
The number of seconds to wait for the OS to return a SIGCHILD to supervisord after the program has been sent a stopsignal. If this number of seconds elapses before supervisord receives a SIGCHILD from the process, supervisord will attempt to kill it with a final SIGKILL.
In addition, programming languages have standard mechanisms to handle shutdown http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29
Futhermore, such a solution is universal and not limited to HTTP apps only.
Is Mesos doesn't do it this way? https://github.com/apache/mesos/blob/2985ae05634038b70f974bbfed6b52fe47231418/src/slave/flags.hpp#L139
see #1579
I would suggest that a graceful shutdown (e.g. to allow removal from a load balancer) would also be part of the transition of old instances during upgrade deployment workflows.
I'm not sure if that was part of the original intention of this issue, but it's the use case I'm researching to accomplish better availability during upgrades (without independently managing multiple marathon apps etc).
Currently trying to solve the graceful rolling upgrades problem and it'd help immensely if the upgrade & restart flow was adjusted as suggested in #1147, e.g.
- New tasks are gradually staged, started and become healthy
- Old tasks are gradually removed from Marathon API and event bus. Resulting in old tasks being removed quickly from service discovery.
- After some timeout old tasks are killed (i.e. using the regular Mesos SIGTERM -> graceperiod -> SIGKILL task shutdown process) .
Services need to trap and handle the SIGTERM signal gracefully, i.e. complete outstanding requests and exit nicely. Which as noted in previous comments is standard POSIX behavior anyway.
Currently trying to very sub-optimally solve the problem by
- Increasing the Mesos grace period parameters to e.g. executor_shutdown_grace_period=60 and docker_stop_timeout=55
- Trapping SIGTERM in services and immediately start failing the health check (e.g. return HTTP 503 Service Unavailable).
- Waiting 45s before actually exiting the service, so that service discovery has time to react. The idea being that both outstanding requests and new incoming requests (initiated before service discovery has reacted to the failing health check) can finish.
You know... if this hasn't been implemented, as a first stab, would you be willing to do the same thing that Apache Aurora does? This would certainly make it easy to move applications from Aurora to Marathon.
The Aurora documentation details how they do it. The gist of it is that the app needs to implement 3 things.
- A
/healthhttp endpoint, which returns a http status code of 200 and the literal text ofok - A
/quitquitquitendpoint which only accepts httpPOSTrequests. When the scheduler (read Marathon) sends a POST here, the application will start a graceful shutdown and immediately start failing any healthcheck to/health - An
/abortabortabortendpoint, which only accepts httpPOSTrequests. Ten seconds from when/quitquitquitis signaled, a second httpPOSTrequest is made to/abortabortabort, which triggers the application to shut down immediately. - After the timeout is hit for
/abortabortabort, then the standard mesos SIGTERM, wait, SIGKILL conventions are followed.
Then in the aurora configuration for that application, it needs to specify a health port, which is the port where these http requests will be made to.
I've got an Aurora aware load balancer, aurproxy, doing http HEAD requests to the /health endpoint every 3 seconds. This results in Aurora being able to do rolling restarts and the load balancer draining instances before they are forcibly killed.
Note that the above three urls are configurable, and there is a patch in the works for the timeouts to be as well. It would be great if Marathon followed this same pattern which, IMO, works beautifully.
@mikljohansson - Did increasing the Mesos grace period work for you? We are looking at tackling it that way for now as well.
Thanks for your thoughts!
My ideal of a graceful shutdown sequence would have these properties:
- Can inform external systems (not just the instance) that an instance is about to be killed.
- Has configurable/pluggable logic for how long to wait before killing the instance.
An implementation which satisfies those could look like this: An app definition could include a set of commands / URIs (much like healthcheck cmd/uri) that Marathon would use to control this process:
drain: this command / URI would be run / POSTed to when a task is scheduled to be killed. This could remove the task from load balancers, etc.is_safe_to_kill: this command/URI would be run/GET from, and the return code would decide whether Marathon will kill the task yet. (Otherwise, it will poll again later.)stop_draining: this is run/POSTed to when we decide to not kill an instance after all.
For convenience, the is_safe_to_kill check should probably get passed the timestamp when draining started, so you could easy implement timeout-based draining. (Remove task from load balancer, wait for N seconds)
Marathon, when it wants to kill a task, would first call drain, then poll is_safe_to_kill until that returns true, then kill the task.
Does anyone on this thread have a working fork they are using today? We're struggling to get a working rev that has a different shutdown grace period. Thanks!
@adomeier sorry for being so slow to respond. We hadn't actually gotten around to trying out the workaround. I've done so now and it does work really well actually. I've written about what's needed to make it work on this page
https://github.com/meltwater/proxymatic#rolling-upgradesrestarts
In essence
- Start Mesos slave with --executor_shutdown_grace_period=60secs --docker_stop_timeout=50secs
- Trap SIGTERM in apps and fail the health check
- Make sure your service discovery proxy uses Marathon event http callbacks and removes tasks that fail their health check immediately. The /v2/tasks endpoint shows health status and has an "alive" flag.
- The load balancer must allow existing connections to finish, HAproxy, Nginx and Pen does this by default so no problem there. Any requests that complete within the grace period (e.g. <50s) should be fine, and most HTTP requests should be short anyway.
Thanks @mikljohansson ! That's super interesting. We ended up getting around it for now as a lot of our apps that maintain state actually spawn a child process so killing the parent allows our child jobs to finish gracefully with out the kill interrupting the transaction. We're continue down an active integration with the tech stack tho and I'm sure we'll see other issues with other apps. Really appreciate your response it's very helpful!
CC - @jolexa
Yea we do exactly the same in our project, we trap SIGTERM https://github.com/eBayClassifiedsGroup/PanteraS/blob/master/frameworks/start.sh#L59 which means that each container have to be started with wrapper.
The workaround to trap SIGTERM and start failing the health check only works when having full control over the services, we have a lot of both our own and 3rd party services. It's also rather involved to implement in some frameworks/languages we've noticed. Neither is it very immediate, since the load balancers needs to wait up to HealthCheckDefinition.intervalSeconds to detect that the task is draining.
Our motivation for is that we'd like the ability to continuously roll out new app versions without interruption to service nor fail any requests while the rollout happens. To solve this without having to modify every single service I've investigated some possible routes. An idea I'd very much appreciate feedback on is:
-
Use a task change event (via normal event bus) to detect immediately when Marathon calls
driver.killTask()and remove the task from the load balancers. For example by adding aint64 drained_atfield to MarathonTask and set it whendriver.killTask()is called.This drain-and-update-status could be abstracted being a
TaskTracker.drainTask(...)method that updates thedrainedAtas a normal task state change, which would then trigger an event to be distributed. -
The calls to
driver.killTask()are somewhat spread out in source and tests, so would need some refactoring. But then perhaps not all thedriver.killTask()calls need go viaTaskTracker.drainTask(), modifying only theTaskKillActorthat takes part in rolling upgrades could be a great start. -
This leaves the problem of giving the load balancers some seconds remove the task and prevent new connections from being sent there, before the task is actually sent the SIGTERM. This could be solved using a wrapper script like @sielaq referenced, but even better would be a per-app configurable delay between
TaskTracker.drainTask()anddriver.killTask().This delay could perhaps be implemented by
TaskTracker.determineOverdueTasks()called fromKillOverdueTasksActor, which would scan for and kill tasks whosedrainDelayhas elapsed. This would hopefully ensure that Marathon failures like #2327 had issues with wouldn't impact the draining behaviour.
Some pseudo-code that tries to express this
marathon.proto
message ServiceDefinition {
...
optional int64 drainDelay = 26 [default = 0]; // stored as Millis
}
message MarathonTask {
...
optional int64 drained_at = 12;
}
TaskTracker.scala
def getDefinition(taskId: String): ServiceDefinition = ...
def drainTask(taskId: String) {
val builder = getTask(taskId).toBuilder
builder.setDrainedAt(System.currentTimeMillis)
updateTask(builder.build())
if getDefinition(taskId).drainDelay == 0 {
driver.killTask(taskId)
}
}
def determineOverdueTasks(now: Timestamp): Iterable[MarathonTask] = {
...
else if (task.hasDrainedAt && task.getDrainedAt < (nowMillis - getDefinition(task.getId).drainDelay)) {
true
}
}