celery-keepalive 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- celery_keepalive-0.1.0/LICENSE +21 -0
- celery_keepalive-0.1.0/PKG-INFO +227 -0
- celery_keepalive-0.1.0/README.md +200 -0
- celery_keepalive-0.1.0/pyproject.toml +93 -0
- celery_keepalive-0.1.0/pyproject.toml.orig +71 -0
- celery_keepalive-0.1.0/src/celery_keepalive/__init__.py +5 -0
- celery_keepalive-0.1.0/src/celery_keepalive/agent.py +87 -0
- celery_keepalive-0.1.0/src/celery_keepalive/bootstep.py +83 -0
- celery_keepalive-0.1.0/src/celery_keepalive/channels.py +88 -0
- celery_keepalive-0.1.0/src/celery_keepalive/draining.py +84 -0
- celery_keepalive-0.1.0/src/celery_keepalive/py.typed +0 -0
- celery_keepalive-0.1.0/src/celery_keepalive/renewals.py +79 -0
- celery_keepalive-0.1.0/src/celery_keepalive/settings.py +73 -0
- celery_keepalive-0.1.0/src/celery_keepalive/versions.py +8 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kevin Carrogan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: celery-keepalive
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Keeps ECS from stopping a Celery worker while it is running a job.
|
|
5
|
+
Keywords: celery,ecs,aws,scale-in,task-protection,deployment
|
|
6
|
+
Author: Kevin Carrogan
|
|
7
|
+
Author-email: Kevin Carrogan <kevin@carrogan.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: Celery
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Dist: celery>=5.7.0
|
|
21
|
+
Requires-Dist: pydantic>=2.14.4
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Project-URL: Homepage, https://github.com/kevincarrogan/celery-keepalive
|
|
24
|
+
Project-URL: Changelog, https://github.com/kevincarrogan/celery-keepalive/blob/main/CHANGELOG.md
|
|
25
|
+
Project-URL: Issues, https://github.com/kevincarrogan/celery-keepalive/issues
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# celery-keepalive
|
|
29
|
+
|
|
30
|
+
Keeps ECS from stopping a Celery worker while it is running a job.
|
|
31
|
+
|
|
32
|
+
## Background
|
|
33
|
+
|
|
34
|
+
If you run Celery workers as an ECS service, ECS stops them when it scales in
|
|
35
|
+
or replaces tasks during a deployment, whether or not they have work in
|
|
36
|
+
flight.
|
|
37
|
+
SIGTERM starts Celery's warm shutdown, but ECS sends SIGKILL after the stop
|
|
38
|
+
timeout (at most 120 seconds on Fargate), so long-running jobs are killed.
|
|
39
|
+
|
|
40
|
+
celery-keepalive uses ECS [task scale-in protection][protection] to stop that:
|
|
41
|
+
|
|
42
|
+
- **Scale-in:** while a worker is running a job, ECS won't pick its task to
|
|
43
|
+
stop. Shortly after the worker goes idle, ECS can stop it as normal.
|
|
44
|
+
- **Deployments:** workers on the old version stop taking new jobs, finish the
|
|
45
|
+
ones they have, and are then replaced.
|
|
46
|
+
- **Failure:** if a worker dies, or a job hangs past its
|
|
47
|
+
[time limit](#recommended-celery-settings), the protection runs out on its
|
|
48
|
+
own, so a broken worker never blocks scaling or deployments for long.
|
|
49
|
+
|
|
50
|
+
[docs/design.md](https://github.com/kevincarrogan/celery-keepalive/blob/main/docs/design.md) explains how it works, and
|
|
51
|
+
[how to debug it](https://github.com/kevincarrogan/celery-keepalive/blob/main/docs/design.md#debugging).
|
|
52
|
+
|
|
53
|
+
It is in early development, so its settings and interfaces may still change
|
|
54
|
+
before 1.0.
|
|
55
|
+
|
|
56
|
+
[protection]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-scale-in-protection.html
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
uv add celery-keepalive
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Requirements
|
|
65
|
+
|
|
66
|
+
- Python 3.12 or later
|
|
67
|
+
- Celery workers running as ECS tasks, on Fargate or EC2
|
|
68
|
+
- A task IAM role that allows `ecs:UpdateTaskProtection`
|
|
69
|
+
- For [draining during deployments](#deployments) with the default channel, a
|
|
70
|
+
broker that supports Celery's remote control, such as Redis or RabbitMQ.
|
|
71
|
+
Amazon SQS doesn't, but you can [use another channel](#using-another-channel).
|
|
72
|
+
|
|
73
|
+
## Usage
|
|
74
|
+
|
|
75
|
+
Add the bootstep where you create your Celery app. In a Django project that is
|
|
76
|
+
usually `proj/celery.py`:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from celery import Celery
|
|
80
|
+
from celery_keepalive import KeepaliveStep
|
|
81
|
+
|
|
82
|
+
app = Celery("myapp")
|
|
83
|
+
app.steps["worker"].add(KeepaliveStep)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
With the default [configuration](#configuration), each job protects its ECS
|
|
87
|
+
task for the next 2 minutes as soon as it starts, and renews that every 30
|
|
88
|
+
seconds until it finishes. Nothing removes protection: within 2 minutes of
|
|
89
|
+
the last job finishing it runs out, and ECS can stop the task as normal.
|
|
90
|
+
|
|
91
|
+
This also works when a worker runs several jobs at once, or one ECS task runs
|
|
92
|
+
several workers: the task stays protected while any job is running.
|
|
93
|
+
|
|
94
|
+
If the ECS agent fails or doesn't answer within a couple of seconds, the job
|
|
95
|
+
runs regardless. The bootstep logs a warning and tries again at the next
|
|
96
|
+
renewal.
|
|
97
|
+
|
|
98
|
+
Outside ECS, such as in local development, the bootstep logs once that it is
|
|
99
|
+
disabled and does nothing else. It tells the two apart by whether ECS has set
|
|
100
|
+
`ECS_AGENT_URI`.
|
|
101
|
+
|
|
102
|
+
### Deployments
|
|
103
|
+
|
|
104
|
+
When a worker starts, it tells the other workers its version over your Celery
|
|
105
|
+
broker. A worker that hears a different version stops taking new jobs and
|
|
106
|
+
finishes the ones it has. Its protection then runs out, and ECS replaces it.
|
|
107
|
+
Whichever version started most recently wins, so a rollback works the same
|
|
108
|
+
way.
|
|
109
|
+
|
|
110
|
+
A worker's version comes from the `GIT_COMMIT` environment variable by
|
|
111
|
+
default. A worker with no version neither announces itself nor drains.
|
|
112
|
+
|
|
113
|
+
To work the version out another way, such as from a file baked into the
|
|
114
|
+
image, write a function that returns it, or `None` for no version, and give
|
|
115
|
+
its dotted path in `keepalive_version`:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
def release_from_image() -> str | None:
|
|
119
|
+
"""Called once per worker, as it starts."""
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
app.conf.keepalive_version = "myproject.versions.release_from_image"
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
One catch: if a release's new workers start, announce themselves and then
|
|
127
|
+
crash, the old workers have already stopped taking jobs. Jobs wait on the
|
|
128
|
+
queue, and nothing is lost, until ECS rolls the deployment back or you deploy
|
|
129
|
+
again.
|
|
130
|
+
|
|
131
|
+
#### Using another channel
|
|
132
|
+
|
|
133
|
+
Workers announce and hear versions through a channel class. The default,
|
|
134
|
+
`celery_keepalive.channels.RemoteControlChannel`, uses Celery's remote
|
|
135
|
+
control. To use something else, such as a record in SSM Parameter Store that
|
|
136
|
+
workers poll, write a class with these methods and give its dotted path in
|
|
137
|
+
`keepalive_version_channel`. Subclassing `VersionChannel` lets your type
|
|
138
|
+
checker hold it to the contract:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
from collections.abc import Callable
|
|
142
|
+
|
|
143
|
+
from celery import Celery
|
|
144
|
+
from celery_keepalive import VersionChannel
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class MyVersionChannel(VersionChannel):
|
|
148
|
+
def __init__(self, app: Celery) -> None:
|
|
149
|
+
"""Called once per worker, as it starts."""
|
|
150
|
+
|
|
151
|
+
def announce(self, version: str) -> None:
|
|
152
|
+
"""Tell the other workers this worker's version."""
|
|
153
|
+
|
|
154
|
+
def listen(self, on_version: Callable[[str], None]) -> None:
|
|
155
|
+
"""Call on_version with every version heard from now on."""
|
|
156
|
+
|
|
157
|
+
def close(self) -> None:
|
|
158
|
+
"""Stop listening: the worker is stopping."""
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
app.conf.keepalive_version_channel = "myproject.channels.MyVersionChannel"
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
The channel only carries versions. celery-keepalive decides whether a version
|
|
166
|
+
it hears means this worker should drain, and stops it taking new jobs.
|
|
167
|
+
|
|
168
|
+
## Configuration
|
|
169
|
+
|
|
170
|
+
Settings go in your Celery config, alongside the rest:
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
app.conf.keepalive_check_interval = 30 # seconds
|
|
174
|
+
app.conf.keepalive_protection_minutes = 2
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
| Setting | Default | What it does |
|
|
178
|
+
| ------------------------------ | ------------------------------------------------ | ----------------------------------------------------------------------------- |
|
|
179
|
+
| `keepalive_check_interval` | `30` | Seconds between renewals of a running job's protection. |
|
|
180
|
+
| `keepalive_protection_minutes` | `2` | How long each protection lasts, and so how long an idle task stays protected. |
|
|
181
|
+
| `keepalive_version` | `celery_keepalive.versions.from_git_commit` | The function that returns the worker's version, which it announces on start. |
|
|
182
|
+
| `keepalive_version_channel` | `celery_keepalive.channels.RemoteControlChannel` | The class workers announce and hear versions through. |
|
|
183
|
+
|
|
184
|
+
`keepalive_protection_minutes` must be a whole number from 1 to 2880 (48
|
|
185
|
+
hours), which are ECS's limits, and `keepalive_check_interval` must be shorter
|
|
186
|
+
than it. A worker with a setting outside these limits refuses to start, with
|
|
187
|
+
an error naming the setting. It checks them outside ECS too, so a bad value
|
|
188
|
+
shows up in local development before it reaches a deployment.
|
|
189
|
+
|
|
190
|
+
## Recommended Celery settings
|
|
191
|
+
|
|
192
|
+
These aren't required, but they make the most of celery-keepalive:
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
app.conf.task_acks_late = True
|
|
196
|
+
app.conf.worker_prefetch_multiplier = 1
|
|
197
|
+
app.conf.task_time_limit = 60 * 60 # seconds; longer than your longest job
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
- **`task_acks_late`:** a job is acknowledged when it finishes, not when it
|
|
201
|
+
starts. If a worker is killed anyway, for example a hung worker whose
|
|
202
|
+
protection ran out, the job goes back on the queue instead of being lost.
|
|
203
|
+
The trade-off is that a job can run twice, so your tasks need to be safe to
|
|
204
|
+
repeat.
|
|
205
|
+
- **`worker_prefetch_multiplier = 1`:** a busy worker doesn't hold on to jobs
|
|
206
|
+
it hasn't started, so other workers can run them, and a worker that is
|
|
207
|
+
draining for a deployment has less to finish.
|
|
208
|
+
- **`task_time_limit`:** Celery kills a job that runs longer than this. A job
|
|
209
|
+
keeps its task protected for as long as it runs, so without a time limit a
|
|
210
|
+
job that hangs keeps its task protected forever. Set it longer than your
|
|
211
|
+
longest job.
|
|
212
|
+
|
|
213
|
+
## Contributing
|
|
214
|
+
|
|
215
|
+
Issues and pull requests are welcome. To set up and run the checks:
|
|
216
|
+
|
|
217
|
+
```sh
|
|
218
|
+
just setup
|
|
219
|
+
just check
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`just check` includes the end-to-end tests, which run a Docker Compose stack,
|
|
223
|
+
so it needs Docker running. `just test` runs only the unit tests, without it.
|
|
224
|
+
|
|
225
|
+
## License
|
|
226
|
+
|
|
227
|
+
[MIT](https://github.com/kevincarrogan/celery-keepalive/blob/main/LICENSE)
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# celery-keepalive
|
|
2
|
+
|
|
3
|
+
Keeps ECS from stopping a Celery worker while it is running a job.
|
|
4
|
+
|
|
5
|
+
## Background
|
|
6
|
+
|
|
7
|
+
If you run Celery workers as an ECS service, ECS stops them when it scales in
|
|
8
|
+
or replaces tasks during a deployment, whether or not they have work in
|
|
9
|
+
flight.
|
|
10
|
+
SIGTERM starts Celery's warm shutdown, but ECS sends SIGKILL after the stop
|
|
11
|
+
timeout (at most 120 seconds on Fargate), so long-running jobs are killed.
|
|
12
|
+
|
|
13
|
+
celery-keepalive uses ECS [task scale-in protection][protection] to stop that:
|
|
14
|
+
|
|
15
|
+
- **Scale-in:** while a worker is running a job, ECS won't pick its task to
|
|
16
|
+
stop. Shortly after the worker goes idle, ECS can stop it as normal.
|
|
17
|
+
- **Deployments:** workers on the old version stop taking new jobs, finish the
|
|
18
|
+
ones they have, and are then replaced.
|
|
19
|
+
- **Failure:** if a worker dies, or a job hangs past its
|
|
20
|
+
[time limit](#recommended-celery-settings), the protection runs out on its
|
|
21
|
+
own, so a broken worker never blocks scaling or deployments for long.
|
|
22
|
+
|
|
23
|
+
[docs/design.md](https://github.com/kevincarrogan/celery-keepalive/blob/main/docs/design.md) explains how it works, and
|
|
24
|
+
[how to debug it](https://github.com/kevincarrogan/celery-keepalive/blob/main/docs/design.md#debugging).
|
|
25
|
+
|
|
26
|
+
It is in early development, so its settings and interfaces may still change
|
|
27
|
+
before 1.0.
|
|
28
|
+
|
|
29
|
+
[protection]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-scale-in-protection.html
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
uv add celery-keepalive
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Requirements
|
|
38
|
+
|
|
39
|
+
- Python 3.12 or later
|
|
40
|
+
- Celery workers running as ECS tasks, on Fargate or EC2
|
|
41
|
+
- A task IAM role that allows `ecs:UpdateTaskProtection`
|
|
42
|
+
- For [draining during deployments](#deployments) with the default channel, a
|
|
43
|
+
broker that supports Celery's remote control, such as Redis or RabbitMQ.
|
|
44
|
+
Amazon SQS doesn't, but you can [use another channel](#using-another-channel).
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
Add the bootstep where you create your Celery app. In a Django project that is
|
|
49
|
+
usually `proj/celery.py`:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from celery import Celery
|
|
53
|
+
from celery_keepalive import KeepaliveStep
|
|
54
|
+
|
|
55
|
+
app = Celery("myapp")
|
|
56
|
+
app.steps["worker"].add(KeepaliveStep)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
With the default [configuration](#configuration), each job protects its ECS
|
|
60
|
+
task for the next 2 minutes as soon as it starts, and renews that every 30
|
|
61
|
+
seconds until it finishes. Nothing removes protection: within 2 minutes of
|
|
62
|
+
the last job finishing it runs out, and ECS can stop the task as normal.
|
|
63
|
+
|
|
64
|
+
This also works when a worker runs several jobs at once, or one ECS task runs
|
|
65
|
+
several workers: the task stays protected while any job is running.
|
|
66
|
+
|
|
67
|
+
If the ECS agent fails or doesn't answer within a couple of seconds, the job
|
|
68
|
+
runs regardless. The bootstep logs a warning and tries again at the next
|
|
69
|
+
renewal.
|
|
70
|
+
|
|
71
|
+
Outside ECS, such as in local development, the bootstep logs once that it is
|
|
72
|
+
disabled and does nothing else. It tells the two apart by whether ECS has set
|
|
73
|
+
`ECS_AGENT_URI`.
|
|
74
|
+
|
|
75
|
+
### Deployments
|
|
76
|
+
|
|
77
|
+
When a worker starts, it tells the other workers its version over your Celery
|
|
78
|
+
broker. A worker that hears a different version stops taking new jobs and
|
|
79
|
+
finishes the ones it has. Its protection then runs out, and ECS replaces it.
|
|
80
|
+
Whichever version started most recently wins, so a rollback works the same
|
|
81
|
+
way.
|
|
82
|
+
|
|
83
|
+
A worker's version comes from the `GIT_COMMIT` environment variable by
|
|
84
|
+
default. A worker with no version neither announces itself nor drains.
|
|
85
|
+
|
|
86
|
+
To work the version out another way, such as from a file baked into the
|
|
87
|
+
image, write a function that returns it, or `None` for no version, and give
|
|
88
|
+
its dotted path in `keepalive_version`:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
def release_from_image() -> str | None:
|
|
92
|
+
"""Called once per worker, as it starts."""
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
app.conf.keepalive_version = "myproject.versions.release_from_image"
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
One catch: if a release's new workers start, announce themselves and then
|
|
100
|
+
crash, the old workers have already stopped taking jobs. Jobs wait on the
|
|
101
|
+
queue, and nothing is lost, until ECS rolls the deployment back or you deploy
|
|
102
|
+
again.
|
|
103
|
+
|
|
104
|
+
#### Using another channel
|
|
105
|
+
|
|
106
|
+
Workers announce and hear versions through a channel class. The default,
|
|
107
|
+
`celery_keepalive.channels.RemoteControlChannel`, uses Celery's remote
|
|
108
|
+
control. To use something else, such as a record in SSM Parameter Store that
|
|
109
|
+
workers poll, write a class with these methods and give its dotted path in
|
|
110
|
+
`keepalive_version_channel`. Subclassing `VersionChannel` lets your type
|
|
111
|
+
checker hold it to the contract:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from collections.abc import Callable
|
|
115
|
+
|
|
116
|
+
from celery import Celery
|
|
117
|
+
from celery_keepalive import VersionChannel
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class MyVersionChannel(VersionChannel):
|
|
121
|
+
def __init__(self, app: Celery) -> None:
|
|
122
|
+
"""Called once per worker, as it starts."""
|
|
123
|
+
|
|
124
|
+
def announce(self, version: str) -> None:
|
|
125
|
+
"""Tell the other workers this worker's version."""
|
|
126
|
+
|
|
127
|
+
def listen(self, on_version: Callable[[str], None]) -> None:
|
|
128
|
+
"""Call on_version with every version heard from now on."""
|
|
129
|
+
|
|
130
|
+
def close(self) -> None:
|
|
131
|
+
"""Stop listening: the worker is stopping."""
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
app.conf.keepalive_version_channel = "myproject.channels.MyVersionChannel"
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The channel only carries versions. celery-keepalive decides whether a version
|
|
139
|
+
it hears means this worker should drain, and stops it taking new jobs.
|
|
140
|
+
|
|
141
|
+
## Configuration
|
|
142
|
+
|
|
143
|
+
Settings go in your Celery config, alongside the rest:
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
app.conf.keepalive_check_interval = 30 # seconds
|
|
147
|
+
app.conf.keepalive_protection_minutes = 2
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
| Setting | Default | What it does |
|
|
151
|
+
| ------------------------------ | ------------------------------------------------ | ----------------------------------------------------------------------------- |
|
|
152
|
+
| `keepalive_check_interval` | `30` | Seconds between renewals of a running job's protection. |
|
|
153
|
+
| `keepalive_protection_minutes` | `2` | How long each protection lasts, and so how long an idle task stays protected. |
|
|
154
|
+
| `keepalive_version` | `celery_keepalive.versions.from_git_commit` | The function that returns the worker's version, which it announces on start. |
|
|
155
|
+
| `keepalive_version_channel` | `celery_keepalive.channels.RemoteControlChannel` | The class workers announce and hear versions through. |
|
|
156
|
+
|
|
157
|
+
`keepalive_protection_minutes` must be a whole number from 1 to 2880 (48
|
|
158
|
+
hours), which are ECS's limits, and `keepalive_check_interval` must be shorter
|
|
159
|
+
than it. A worker with a setting outside these limits refuses to start, with
|
|
160
|
+
an error naming the setting. It checks them outside ECS too, so a bad value
|
|
161
|
+
shows up in local development before it reaches a deployment.
|
|
162
|
+
|
|
163
|
+
## Recommended Celery settings
|
|
164
|
+
|
|
165
|
+
These aren't required, but they make the most of celery-keepalive:
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
app.conf.task_acks_late = True
|
|
169
|
+
app.conf.worker_prefetch_multiplier = 1
|
|
170
|
+
app.conf.task_time_limit = 60 * 60 # seconds; longer than your longest job
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
- **`task_acks_late`:** a job is acknowledged when it finishes, not when it
|
|
174
|
+
starts. If a worker is killed anyway, for example a hung worker whose
|
|
175
|
+
protection ran out, the job goes back on the queue instead of being lost.
|
|
176
|
+
The trade-off is that a job can run twice, so your tasks need to be safe to
|
|
177
|
+
repeat.
|
|
178
|
+
- **`worker_prefetch_multiplier = 1`:** a busy worker doesn't hold on to jobs
|
|
179
|
+
it hasn't started, so other workers can run them, and a worker that is
|
|
180
|
+
draining for a deployment has less to finish.
|
|
181
|
+
- **`task_time_limit`:** Celery kills a job that runs longer than this. A job
|
|
182
|
+
keeps its task protected for as long as it runs, so without a time limit a
|
|
183
|
+
job that hangs keeps its task protected forever. Set it longer than your
|
|
184
|
+
longest job.
|
|
185
|
+
|
|
186
|
+
## Contributing
|
|
187
|
+
|
|
188
|
+
Issues and pull requests are welcome. To set up and run the checks:
|
|
189
|
+
|
|
190
|
+
```sh
|
|
191
|
+
just setup
|
|
192
|
+
just check
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`just check` includes the end-to-end tests, which run a Docker Compose stack,
|
|
196
|
+
so it needs Docker running. `just test` runs only the unit tests, without it.
|
|
197
|
+
|
|
198
|
+
## License
|
|
199
|
+
|
|
200
|
+
[MIT](https://github.com/kevincarrogan/celery-keepalive/blob/main/LICENSE)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "celery-keepalive"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Keeps ECS from stopping a Celery worker while it is running a job."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.12"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"celery>=5.7.0",
|
|
11
|
+
"pydantic>=2.14.4",
|
|
12
|
+
]
|
|
13
|
+
keywords = [
|
|
14
|
+
"celery",
|
|
15
|
+
"ecs",
|
|
16
|
+
"aws",
|
|
17
|
+
"scale-in",
|
|
18
|
+
"task-protection",
|
|
19
|
+
"deployment",
|
|
20
|
+
]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 3 - Alpha",
|
|
23
|
+
"Framework :: Celery",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"Operating System :: OS Independent",
|
|
26
|
+
"Programming Language :: Python :: 3",
|
|
27
|
+
"Programming Language :: Python :: 3.12",
|
|
28
|
+
"Programming Language :: Python :: 3.13",
|
|
29
|
+
"Programming Language :: Python :: 3.14",
|
|
30
|
+
"Topic :: System :: Distributed Computing",
|
|
31
|
+
"Typing :: Typed",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[[project.authors]]
|
|
35
|
+
name = "Kevin Carrogan"
|
|
36
|
+
email = "kevin@carrogan.com"
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/kevincarrogan/celery-keepalive"
|
|
40
|
+
Changelog = "https://github.com/kevincarrogan/celery-keepalive/blob/main/CHANGELOG.md"
|
|
41
|
+
Issues = "https://github.com/kevincarrogan/celery-keepalive/issues"
|
|
42
|
+
|
|
43
|
+
[build-system]
|
|
44
|
+
requires = ["uv_build>=0.12.23,<0.13.0"]
|
|
45
|
+
build-backend = "uv_build"
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
testpaths = ["tests"]
|
|
49
|
+
|
|
50
|
+
[tool.ruff]
|
|
51
|
+
target-version = "py312"
|
|
52
|
+
|
|
53
|
+
[tool.ruff.lint]
|
|
54
|
+
select = [
|
|
55
|
+
"E",
|
|
56
|
+
"F",
|
|
57
|
+
"W",
|
|
58
|
+
"I",
|
|
59
|
+
"B",
|
|
60
|
+
"UP",
|
|
61
|
+
"SIM",
|
|
62
|
+
"RUF",
|
|
63
|
+
"TID",
|
|
64
|
+
"PLC0415",
|
|
65
|
+
"COM812",
|
|
66
|
+
]
|
|
67
|
+
ignore = ["E501"]
|
|
68
|
+
|
|
69
|
+
[tool.ruff.lint.flake8-tidy-imports]
|
|
70
|
+
ban-relative-imports = "all"
|
|
71
|
+
|
|
72
|
+
[tool.ruff.lint.isort]
|
|
73
|
+
force-single-line = true
|
|
74
|
+
|
|
75
|
+
[tool.mypy]
|
|
76
|
+
strict = true
|
|
77
|
+
files = [
|
|
78
|
+
"src",
|
|
79
|
+
"tests",
|
|
80
|
+
"e2e",
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
[dependency-groups]
|
|
84
|
+
dev = [
|
|
85
|
+
"celery-types>=0.26.0",
|
|
86
|
+
"mypy>=2.4.1",
|
|
87
|
+
"pre-commit>=4.7.0",
|
|
88
|
+
"pytest>=9.2.0",
|
|
89
|
+
"pytest-httpserver>=1.2.1",
|
|
90
|
+
"ruff>=0.17.6",
|
|
91
|
+
"testcontainers>=4.15.0",
|
|
92
|
+
"types-docker>=7.2.0.20261122",
|
|
93
|
+
]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "celery-keepalive"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Keeps ECS from stopping a Celery worker while it is running a job."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Kevin Carrogan", email = "kevin@carrogan.com" }
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"celery>=5.7.0",
|
|
14
|
+
"pydantic>=2.14.4",
|
|
15
|
+
]
|
|
16
|
+
keywords = ["celery", "ecs", "aws", "scale-in", "task-protection", "deployment"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Framework :: Celery",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
|
+
"Topic :: System :: Distributed Computing",
|
|
27
|
+
"Typing :: Typed",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/kevincarrogan/celery-keepalive"
|
|
32
|
+
Changelog = "https://github.com/kevincarrogan/celery-keepalive/blob/main/CHANGELOG.md"
|
|
33
|
+
Issues = "https://github.com/kevincarrogan/celery-keepalive/issues"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["uv_build>=0.12.23,<0.13.0"]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
testpaths = ["tests"]
|
|
41
|
+
|
|
42
|
+
[tool.ruff]
|
|
43
|
+
target-version = "py312"
|
|
44
|
+
|
|
45
|
+
[tool.ruff.lint]
|
|
46
|
+
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "TID", "PLC0415", "COM812"]
|
|
47
|
+
# The formatter owns line length; this only fires on long docstrings and strings.
|
|
48
|
+
ignore = ["E501"]
|
|
49
|
+
|
|
50
|
+
[tool.ruff.lint.flake8-tidy-imports]
|
|
51
|
+
ban-relative-imports = "all"
|
|
52
|
+
|
|
53
|
+
[tool.ruff.lint.isort]
|
|
54
|
+
# One import per line, always.
|
|
55
|
+
force-single-line = true
|
|
56
|
+
|
|
57
|
+
[tool.mypy]
|
|
58
|
+
strict = true
|
|
59
|
+
files = ["src", "tests", "e2e"]
|
|
60
|
+
|
|
61
|
+
[dependency-groups]
|
|
62
|
+
dev = [
|
|
63
|
+
"celery-types>=0.26.0",
|
|
64
|
+
"mypy>=2.4.1",
|
|
65
|
+
"pre-commit>=4.7.0",
|
|
66
|
+
"pytest>=9.2.0",
|
|
67
|
+
"pytest-httpserver>=1.2.1",
|
|
68
|
+
"ruff>=0.17.6",
|
|
69
|
+
"testcontainers>=4.15.0",
|
|
70
|
+
"types-docker>=7.2.0.20261122",
|
|
71
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""The ECS agent in each task, which protects the task from scale-in."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import urllib.request
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
from pydantic import ConfigDict
|
|
8
|
+
from pydantic import ValidationError
|
|
9
|
+
from pydantic.alias_generators import to_pascal
|
|
10
|
+
|
|
11
|
+
# How long a call to the agent may take before it is given up on, so an agent
|
|
12
|
+
# that never answers can't hold up a job.
|
|
13
|
+
AGENT_TIMEOUT_SECONDS = 2
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class EcsAgent:
|
|
17
|
+
"""Asks the task's ECS agent to protect the task."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, agent_uri: str, protection_minutes: int) -> None:
|
|
20
|
+
self._protection_url = f"{agent_uri}/task-protection/v1/state"
|
|
21
|
+
self._protection_minutes = protection_minutes
|
|
22
|
+
|
|
23
|
+
def protect(self) -> None:
|
|
24
|
+
"""Protects the task for the next protection_minutes, or raises
|
|
25
|
+
ProtectionFailed."""
|
|
26
|
+
body = {
|
|
27
|
+
"ProtectionEnabled": True,
|
|
28
|
+
"ExpiresInMinutes": self._protection_minutes,
|
|
29
|
+
}
|
|
30
|
+
request = urllib.request.Request(
|
|
31
|
+
self._protection_url,
|
|
32
|
+
data=json.dumps(body).encode(),
|
|
33
|
+
headers={"Content-Type": "application/json"},
|
|
34
|
+
method="PUT",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
with urllib.request.urlopen(
|
|
39
|
+
request,
|
|
40
|
+
timeout=AGENT_TIMEOUT_SECONDS,
|
|
41
|
+
) as response:
|
|
42
|
+
reply_json = response.read()
|
|
43
|
+
except OSError as error:
|
|
44
|
+
raise ProtectionFailed(str(error)) from error
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
reply = ProtectionReply.model_validate_json(reply_json)
|
|
48
|
+
except ValidationError as error:
|
|
49
|
+
raise ProtectionFailed("the agent's reply was not understood") from error
|
|
50
|
+
reply.raise_for_reported_problem()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ProtectionFailed(Exception):
|
|
54
|
+
"""The task is not protected: the agent couldn't be reached, or answered
|
|
55
|
+
but not to say the task is protected."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class AgentFailure(BaseModel):
|
|
59
|
+
"""ECS refused to protect the task, as the agent reports it."""
|
|
60
|
+
|
|
61
|
+
model_config = ConfigDict(alias_generator=to_pascal)
|
|
62
|
+
|
|
63
|
+
reason: str
|
|
64
|
+
detail: str
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class AgentError(BaseModel):
|
|
68
|
+
"""The agent couldn't ask ECS to protect the task, as it reports it."""
|
|
69
|
+
|
|
70
|
+
model_config = ConfigDict(alias_generator=to_pascal)
|
|
71
|
+
|
|
72
|
+
code: str
|
|
73
|
+
message: str
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ProtectionReply(BaseModel):
|
|
77
|
+
"""The agent's reply to a request to protect the task."""
|
|
78
|
+
|
|
79
|
+
failure: AgentFailure | None = None
|
|
80
|
+
error: AgentError | None = None
|
|
81
|
+
|
|
82
|
+
def raise_for_reported_problem(self) -> None:
|
|
83
|
+
"""The agent reports a problem as a "failure" or an "error"."""
|
|
84
|
+
if self.failure is not None:
|
|
85
|
+
raise ProtectionFailed(f"{self.failure.reason}: {self.failure.detail}")
|
|
86
|
+
if self.error is not None:
|
|
87
|
+
raise ProtectionFailed(f"{self.error.code}: {self.error.message}")
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
from typing import Protocol
|
|
4
|
+
|
|
5
|
+
from celery import Celery
|
|
6
|
+
from celery import bootsteps
|
|
7
|
+
from celery.signals import task_postrun
|
|
8
|
+
from celery.signals import task_prerun
|
|
9
|
+
|
|
10
|
+
from celery_keepalive.agent import EcsAgent
|
|
11
|
+
from celery_keepalive.draining import Consumer
|
|
12
|
+
from celery_keepalive.draining import Draining
|
|
13
|
+
from celery_keepalive.renewals import JobRenewals
|
|
14
|
+
from celery_keepalive.settings import settings
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Worker(Protocol):
|
|
20
|
+
"""The worker Celery builds the step with. The step reads its app config,
|
|
21
|
+
and drains its consumer."""
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def app(self) -> Celery: ...
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def consumer(self) -> Consumer: ...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class KeepaliveStep(bootsteps.StartStopStep):
|
|
31
|
+
"""Keeps ECS from stopping the worker's task while it is running a job."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, worker: Worker, **kwargs: object) -> None:
|
|
34
|
+
configured = settings(worker.app)
|
|
35
|
+
# Draining, once the worker has a version to drain by.
|
|
36
|
+
self._draining: Draining | None = None
|
|
37
|
+
protection_minutes = configured.keepalive_protection_minutes
|
|
38
|
+
check_interval_seconds = configured.keepalive_check_interval
|
|
39
|
+
|
|
40
|
+
agent_uri = os.environ.get("ECS_AGENT_URI")
|
|
41
|
+
if agent_uri is None:
|
|
42
|
+
logger.info("celery-keepalive disabled: ECS_AGENT_URI is not set")
|
|
43
|
+
return
|
|
44
|
+
|
|
45
|
+
version = configured.keepalive_version()
|
|
46
|
+
logger.info(
|
|
47
|
+
"celery-keepalive enabled: protecting for %d minutes, renewing "
|
|
48
|
+
"every %g seconds, %s",
|
|
49
|
+
protection_minutes,
|
|
50
|
+
check_interval_seconds,
|
|
51
|
+
"with no version" if version is None else f"as version {version}",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
self._renewals = JobRenewals(
|
|
55
|
+
EcsAgent(agent_uri, protection_minutes),
|
|
56
|
+
protection_minutes,
|
|
57
|
+
check_interval_seconds,
|
|
58
|
+
)
|
|
59
|
+
task_prerun.connect(self._start_protecting)
|
|
60
|
+
task_postrun.connect(self._stop_protecting)
|
|
61
|
+
|
|
62
|
+
if version is None:
|
|
63
|
+
return
|
|
64
|
+
self._draining = Draining(
|
|
65
|
+
version,
|
|
66
|
+
configured.keepalive_version_channel(worker.app),
|
|
67
|
+
worker,
|
|
68
|
+
)
|
|
69
|
+
self._draining.start()
|
|
70
|
+
|
|
71
|
+
def stop(self, worker: Worker) -> None:
|
|
72
|
+
"""Takes on no new jobs once the worker stops, and stops hearing
|
|
73
|
+
versions. Jobs still running, as in a warm shutdown, keep renewing
|
|
74
|
+
until they finish."""
|
|
75
|
+
task_prerun.disconnect(self._start_protecting)
|
|
76
|
+
if self._draining is not None:
|
|
77
|
+
self._draining.stop()
|
|
78
|
+
|
|
79
|
+
def _start_protecting(self, task_id: str, **kwargs: object) -> None:
|
|
80
|
+
self._renewals.start(task_id)
|
|
81
|
+
|
|
82
|
+
def _stop_protecting(self, task_id: str, **kwargs: object) -> None:
|
|
83
|
+
self._renewals.finish(task_id)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Channels workers announce their versions to each other through, for
|
|
2
|
+
keepalive_version_channel."""
|
|
3
|
+
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
from celery import Celery
|
|
8
|
+
from celery.utils.dispatch import Signal
|
|
9
|
+
from celery.worker.control import control_command
|
|
10
|
+
|
|
11
|
+
# The remote control command a worker broadcasts to announce its version.
|
|
12
|
+
VERSION_ANNOUNCED = "keepalive_version_announced"
|
|
13
|
+
|
|
14
|
+
# Sent, with the app as sender, when a worker hears another announce its
|
|
15
|
+
# version over remote control.
|
|
16
|
+
version_heard = Signal(name="keepalive_version_heard")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class VersionChannel(Protocol):
|
|
20
|
+
"""What workers announce their versions to each other through. Built
|
|
21
|
+
with the worker's Celery app, once per worker, as it starts."""
|
|
22
|
+
|
|
23
|
+
def announce(self, version: str) -> None:
|
|
24
|
+
"""Tell the other workers this worker's version."""
|
|
25
|
+
|
|
26
|
+
def listen(self, on_version: Callable[[str], None]) -> None:
|
|
27
|
+
"""Call on_version with every version heard from now on."""
|
|
28
|
+
|
|
29
|
+
def close(self) -> None:
|
|
30
|
+
"""Stop listening: the worker is stopping."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class RemoteControlChannel(VersionChannel):
|
|
34
|
+
"""Announces and hears versions over the broker, with Celery's remote
|
|
35
|
+
control."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, app: Celery) -> None:
|
|
38
|
+
self._app = app
|
|
39
|
+
# The signal receivers listen connected, for close to disconnect.
|
|
40
|
+
self._receivers: list[Callable[..., None]] = []
|
|
41
|
+
|
|
42
|
+
def announce(self, version: str) -> None:
|
|
43
|
+
"""Tells every worker on the broker this worker's version."""
|
|
44
|
+
self._app.control.broadcast(
|
|
45
|
+
VERSION_ANNOUNCED,
|
|
46
|
+
arguments={"version": version},
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def listen(self, on_version: Callable[[str], None]) -> None:
|
|
50
|
+
"""Calls on_version with every version this worker hears."""
|
|
51
|
+
|
|
52
|
+
def receive(sender: Celery, version: str, **kwargs: object) -> None:
|
|
53
|
+
on_version(version)
|
|
54
|
+
|
|
55
|
+
# Held strongly, since nothing else keeps receive alive.
|
|
56
|
+
version_heard.connect(receive, sender=self._app, weak=False)
|
|
57
|
+
self._receivers.append(receive)
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
"""Stops hearing versions: the worker is stopping."""
|
|
61
|
+
for receive in self._receivers:
|
|
62
|
+
version_heard.disconnect(receive, sender=self._app)
|
|
63
|
+
self._receivers.clear()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ControlConsumer(Protocol):
|
|
67
|
+
"""The worker's consumer, as a remote control command sees it."""
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def app(self) -> Celery: ...
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ControlState(Protocol):
|
|
74
|
+
"""What Celery passes a remote control command about the worker."""
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def consumer(self) -> ControlConsumer: ...
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@control_command(name=VERSION_ANNOUNCED)
|
|
81
|
+
def version_announced(
|
|
82
|
+
state: ControlState,
|
|
83
|
+
version: str,
|
|
84
|
+
**kwargs: object,
|
|
85
|
+
) -> dict[str, str]:
|
|
86
|
+
"""Passes a version another worker announced to this worker's listeners."""
|
|
87
|
+
version_heard.send(sender=state.consumer.app, version=version)
|
|
88
|
+
return {"ok": f"heard version {version}"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Stopping old workers taking new jobs once a newer version has started."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
import kombu
|
|
9
|
+
from celery import Celery
|
|
10
|
+
|
|
11
|
+
from celery_keepalive.channels import VersionChannel
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TaskConsumer(Protocol):
|
|
17
|
+
"""The consumer's kombu consumer; draining reads the queues it takes
|
|
18
|
+
jobs from."""
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def queues(self) -> Sequence[kombu.Queue]: ...
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Consumer(Protocol):
|
|
25
|
+
"""The worker's consumer, which takes jobs from the broker."""
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def app(self) -> Celery: ...
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def task_consumer(self) -> TaskConsumer: ...
|
|
32
|
+
|
|
33
|
+
def call_soon(self, callback: Callable[..., object], *args: object) -> object: ...
|
|
34
|
+
|
|
35
|
+
def cancel_task_queue(self, queue: str) -> None: ...
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConsumingWorker(Protocol):
|
|
39
|
+
"""A worker, whose consumer draining stops."""
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def consumer(self) -> Consumer: ...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Draining:
|
|
46
|
+
"""Announces the worker's version, and stops the worker taking new jobs
|
|
47
|
+
when it hears another."""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
version: str,
|
|
52
|
+
channel: VersionChannel,
|
|
53
|
+
worker: ConsumingWorker,
|
|
54
|
+
) -> None:
|
|
55
|
+
self._version = version
|
|
56
|
+
self._channel = channel
|
|
57
|
+
self._worker = worker
|
|
58
|
+
|
|
59
|
+
def start(self) -> None:
|
|
60
|
+
"""Tells the other workers this worker's version, and listens for
|
|
61
|
+
theirs."""
|
|
62
|
+
self._channel.announce(self._version)
|
|
63
|
+
self._channel.listen(self._on_version)
|
|
64
|
+
|
|
65
|
+
def stop(self) -> None:
|
|
66
|
+
"""Stops listening: the worker is stopping."""
|
|
67
|
+
self._channel.close()
|
|
68
|
+
|
|
69
|
+
def _on_version(self, heard_version: str) -> None:
|
|
70
|
+
if heard_version == self._version:
|
|
71
|
+
return
|
|
72
|
+
logger.info(
|
|
73
|
+
"celery-keepalive draining: heard version %s, and this worker is "
|
|
74
|
+
"version %s, so it takes no new jobs",
|
|
75
|
+
heard_version,
|
|
76
|
+
self._version,
|
|
77
|
+
)
|
|
78
|
+
stop_taking_jobs(self._worker.consumer)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def stop_taking_jobs(consumer: Consumer) -> None:
|
|
82
|
+
"""Stops the consumer taking jobs from any of its queues."""
|
|
83
|
+
for queue in consumer.task_consumer.queues:
|
|
84
|
+
consumer.call_soon(consumer.cancel_task_queue, queue.name)
|
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Keeping the task protected for as long as each job runs."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import threading
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
from celery_keepalive.agent import ProtectionFailed
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Protector(Protocol):
|
|
13
|
+
"""Protects the task for the protection period, or raises
|
|
14
|
+
ProtectionFailed."""
|
|
15
|
+
|
|
16
|
+
def protect(self) -> None: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JobRenewals:
|
|
20
|
+
"""Protects the task as each job starts, then renews the protection every
|
|
21
|
+
check interval, on a thread of the job's own, until the job finishes."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
protector: Protector,
|
|
26
|
+
protection_minutes: int,
|
|
27
|
+
check_interval_seconds: float,
|
|
28
|
+
) -> None:
|
|
29
|
+
self._protector = protector
|
|
30
|
+
self._protection_minutes = protection_minutes
|
|
31
|
+
self._check_interval_seconds = check_interval_seconds
|
|
32
|
+
# Each running job's "finished" flag, by the task id Celery gives it.
|
|
33
|
+
self._jobs_finished: dict[str, threading.Event] = {}
|
|
34
|
+
|
|
35
|
+
def start(self, task_id: str) -> None:
|
|
36
|
+
"""Protects the task for the job, and keeps renewing until it
|
|
37
|
+
finishes."""
|
|
38
|
+
self._protect(task_id)
|
|
39
|
+
|
|
40
|
+
job_finished = threading.Event()
|
|
41
|
+
self._jobs_finished[task_id] = job_finished
|
|
42
|
+
threading.Thread(
|
|
43
|
+
target=self._renew_until,
|
|
44
|
+
args=(task_id, job_finished),
|
|
45
|
+
daemon=True,
|
|
46
|
+
).start()
|
|
47
|
+
|
|
48
|
+
def finish(self, task_id: str) -> None:
|
|
49
|
+
"""Stops renewing for the job. Its protection then runs out on its
|
|
50
|
+
own."""
|
|
51
|
+
self._jobs_finished.pop(task_id).set()
|
|
52
|
+
logger.debug(
|
|
53
|
+
"celery-keepalive stopped renewing for job %s: the task's protection "
|
|
54
|
+
"runs out within %d minutes, unless another job renews it",
|
|
55
|
+
task_id,
|
|
56
|
+
self._protection_minutes,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def _renew_until(self, task_id: str, job_finished: threading.Event) -> None:
|
|
60
|
+
while not job_finished.wait(self._check_interval_seconds):
|
|
61
|
+
self._protect(task_id)
|
|
62
|
+
|
|
63
|
+
def _protect(self, task_id: str) -> None:
|
|
64
|
+
"""If protecting fails, the job runs regardless and the next check
|
|
65
|
+
tries again."""
|
|
66
|
+
try:
|
|
67
|
+
self._protector.protect()
|
|
68
|
+
except ProtectionFailed as error:
|
|
69
|
+
logger.warning(
|
|
70
|
+
"celery-keepalive could not protect the task for job %s: %s",
|
|
71
|
+
task_id,
|
|
72
|
+
error,
|
|
73
|
+
)
|
|
74
|
+
return
|
|
75
|
+
logger.debug(
|
|
76
|
+
"celery-keepalive protected the task for %d minutes, for job %s",
|
|
77
|
+
self._protection_minutes,
|
|
78
|
+
task_id,
|
|
79
|
+
)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""celery-keepalive's settings, read from the Celery config and checked."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Self
|
|
5
|
+
|
|
6
|
+
from celery import Celery
|
|
7
|
+
from celery.exceptions import ImproperlyConfigured
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
from pydantic import ConfigDict
|
|
10
|
+
from pydantic import Field
|
|
11
|
+
from pydantic import ImportString
|
|
12
|
+
from pydantic import ValidationError
|
|
13
|
+
from pydantic import model_validator
|
|
14
|
+
|
|
15
|
+
from celery_keepalive.channels import RemoteControlChannel
|
|
16
|
+
from celery_keepalive.channels import VersionChannel
|
|
17
|
+
from celery_keepalive.versions import from_git_commit
|
|
18
|
+
|
|
19
|
+
DEFAULT_PROTECTION_MINUTES = 2
|
|
20
|
+
|
|
21
|
+
# The protection periods ECS accepts, in whole minutes: up to 48 hours.
|
|
22
|
+
MIN_PROTECTION_MINUTES = 1
|
|
23
|
+
MAX_PROTECTION_MINUTES = 2880
|
|
24
|
+
|
|
25
|
+
DEFAULT_CHECK_INTERVAL_SECONDS = 30
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Settings(BaseModel):
|
|
29
|
+
"""The keepalive_ settings, each within the limits it must keep to."""
|
|
30
|
+
|
|
31
|
+
model_config = ConfigDict(frozen=True, validate_default=True)
|
|
32
|
+
|
|
33
|
+
keepalive_protection_minutes: int = Field(
|
|
34
|
+
default=DEFAULT_PROTECTION_MINUTES,
|
|
35
|
+
strict=True,
|
|
36
|
+
ge=MIN_PROTECTION_MINUTES,
|
|
37
|
+
le=MAX_PROTECTION_MINUTES,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
keepalive_check_interval: float = Field(
|
|
41
|
+
default=DEFAULT_CHECK_INTERVAL_SECONDS,
|
|
42
|
+
gt=0,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
keepalive_version: ImportString[Callable[[], str | None]] = Field(
|
|
46
|
+
default=from_git_commit,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
keepalive_version_channel: ImportString[Callable[[Celery], VersionChannel]] = Field(
|
|
50
|
+
default=RemoteControlChannel,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
@model_validator(mode="after")
|
|
54
|
+
def check_interval_renews_before_protection_runs_out(self) -> Self:
|
|
55
|
+
protection_seconds = self.keepalive_protection_minutes * 60
|
|
56
|
+
if self.keepalive_check_interval >= protection_seconds:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"keepalive_check_interval must be less than the protection "
|
|
59
|
+
f"period ({protection_seconds} seconds)",
|
|
60
|
+
)
|
|
61
|
+
return self
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def settings(app: Celery) -> Settings:
|
|
65
|
+
"""The app's keepalive_ settings, or ImproperlyConfigured naming the
|
|
66
|
+
one that is wrong."""
|
|
67
|
+
configured = {
|
|
68
|
+
name: app.conf[name] for name in Settings.model_fields if name in app.conf
|
|
69
|
+
}
|
|
70
|
+
try:
|
|
71
|
+
return Settings.model_validate(configured)
|
|
72
|
+
except ValidationError as error:
|
|
73
|
+
raise ImproperlyConfigured(str(error)) from error
|