| 1 |
from typing import Any, Optional, Union |
| 2 |
|
| 3 |
from django.core.exceptions import ImproperlyConfigured |
| 4 |
from django.core.paginator import Paginator |
| 5 |
from django.db import connections |
| 6 |
from django.http import HttpRequest |
| 7 |
from redis.sentinel import SentinelConnectionPool |
| 8 |
from rq.command import send_stop_job_command |
| 9 |
from rq.cron import CronScheduler |
| 10 |
from rq.executions import Execution |
| 11 |
from rq.job import Job, JobStatus |
| 12 |
from rq.queue import Queue |
| 13 |
from rq.registry import ( |
| 14 |
BaseRegistry, |
| 15 |
DeferredJobRegistry, |
| 16 |
FailedJobRegistry, |
| 17 |
FinishedJobRegistry, |
| 18 |
ScheduledJobRegistry, |
| 19 |
StartedJobRegistry, |
| 20 |
clean_registries, |
| 21 |
) |
| 22 |
from rq.worker import Worker |
| 23 |
from rq.worker_registration import clean_worker_registry |
| 24 |
|
| 25 |
from .connection_utils import get_connection, get_redis_connection, get_unique_connection_configs |
| 26 |
from .cron import DjangoCronScheduler |
| 27 |
from .queues import get_queue_by_index, get_scheduler |
| 28 |
from .settings import get_queues_list |
| 29 |
from .templatetags.django_rq import to_localtime |
| 30 |
|
| 31 |
DEFAULT_ITEMS_PER_PAGE = 100 |
| 32 |
|
| 33 |
|
| 34 |
def paginate( |
| 35 |
request: HttpRequest, num_items: int, items_per_page: int = DEFAULT_ITEMS_PER_PAGE |
| 36 |
) -> tuple[int, list[Union[int, str]], int]: |
| 37 |
"""Returns (page, page_range, offset) for a paginated view. |
| 38 |
|
| 39 |
The page number comes from user input, so it is validated rather than trusted: an |
| 40 |
unparseable or out of range page would otherwise become a negative or oversized Redis |
| 41 |
offset, which silently returns the wrong slice. |
| 42 |
|
| 43 |
`page_range` is elided around the current page, so a queue holding a million jobs links to |
| 44 |
a dozen pages rather than ten thousand. Gaps are marked with `Paginator.ELLIPSIS`, which |
| 45 |
templates render as plain text via the `is_ellipsis` filter. |
| 46 |
""" |
| 47 |
if num_items <= 0: |
| 48 |
return 1, [], 0 |
| 49 |
|
| 50 |
# Paginator only needs a sized sequence to count pages, not the items themselves. |
| 51 |
# `range()` is lazy, so nothing extra is read from Redis. |
| 52 |
paginator = Paginator(range(num_items), items_per_page) |
| 53 |
|
| 54 |
try: |
| 55 |
# Page numbers below 1 are clamped to the first page. `get_page()` would send them |
| 56 |
# to the *last* page, which is a surprising place to land from `?page=0`. |
| 57 |
number = max(1, int(request.GET.get('page', 1))) |
| 58 |
except (TypeError, ValueError): |
| 59 |
number = 1 |
| 60 |
|
| 61 |
# `get_page()` clamps a page past the end to the last page and never raises. |
| 62 |
page = paginator.get_page(number) |
| 63 |
# Up to 10 pages are listed in full; beyond that the range elides to `1 2 … 8 9 10 … 99 100` |
| 64 |
page_range = list(paginator.get_elided_page_range(page.number)) |
| 65 |
return page.number, page_range, items_per_page * (page.number - 1) |
| 66 |
|
| 67 |
|
| 68 |
def get_scheduler_pid(queue: Queue) -> Union[bool, int, None]: |
| 69 |
'''Checks whether there's a scheduler-lock on a particular queue, and returns the PID. |
| 70 |
It Only works with RQ's Built-in RQScheduler. |
| 71 |
When RQ-Scheduler is available returns False |
| 72 |
If not, it checks the RQ's RQScheduler for a scheduler lock in the desired queue |
| 73 |
Note: result might have some delay (1-15 minutes) but it helps visualizing whether the setup is working correctly |
| 74 |
''' |
| 75 |
try: |
| 76 |
# first try get the rq-scheduler |
| 77 |
get_scheduler(queue.name) # should fail if rq_scheduler not present |
| 78 |
return False # Not possible to give useful information without creating a performance issue (redis.keys()) |
| 79 |
except ImproperlyConfigured: |
| 80 |
return queue.scheduler_pid |
| 81 |
except Exception: |
| 82 |
return None |
| 83 |
|
| 84 |
|
| 85 |
_DISPLAYABLE_CONNECTION_KWARGS = ( |
| 86 |
'host', |
| 87 |
'port', |
| 88 |
'db', |
| 89 |
'username', |
| 90 |
'client_name', |
| 91 |
'service_name', |
| 92 |
'sentinels', |
| 93 |
'unix_socket_path', |
| 94 |
'path', |
| 95 |
'socket_timeout', |
| 96 |
'socket_connect_timeout', |
| 97 |
'socket_keepalive', |
| 98 |
'health_check_interval', |
| 99 |
'protocol', |
| 100 |
'encoding', |
| 101 |
'decode_responses', |
| 102 |
) |
| 103 |
|
| 104 |
|
| 105 |
def get_displayable_connection_kwargs(obj: Union[Queue, CronScheduler]) -> dict[str, Any]: |
| 106 |
"""Return safe Redis connection metadata for templates and JSON output. |
| 107 |
|
| 108 |
Only operationally meaningful fields are returned. Secret-bearing values |
| 109 |
and redis-py internals are excluded by the allowlist. |
| 110 |
|
| 111 |
Accepts anything holding a Redis connection: a queue or a cron scheduler. |
| 112 |
|
| 113 |
For Sentinel-backed queues, host and port reflect the first sentinel |
| 114 |
endpoint; sentinels lists all known endpoints; service_name identifies the |
| 115 |
master. |
| 116 |
""" |
| 117 |
pool = obj.connection.connection_pool |
| 118 |
connection_kwargs = pool.connection_kwargs.copy() |
| 119 |
|
| 120 |
if isinstance(pool, SentinelConnectionPool): |
| 121 |
connection_kwargs['service_name'] = getattr(pool, 'service_name', None) |
| 122 |
sentinel_connections = pool.sentinel_manager.sentinels |
| 123 |
sentinel_kwargs = [ |
| 124 |
sentinel.connection_pool.connection_kwargs |
| 125 |
for sentinel in sentinel_connections |
| 126 |
] |
| 127 |
if sentinel_kwargs: |
| 128 |
first_sentinel_kwargs = sentinel_kwargs[0] |
| 129 |
connection_kwargs['host'] = first_sentinel_kwargs.get('host') |
| 130 |
connection_kwargs['port'] = first_sentinel_kwargs.get('port') |
| 131 |
connection_kwargs['sentinels'] = [ |
| 132 |
(kwargs.get('host'), kwargs.get('port')) |
| 133 |
for kwargs in sentinel_kwargs |
| 134 |
if kwargs.get('host') is not None and kwargs.get('port') is not None |
| 135 |
] |
| 136 |
|
| 137 |
return { |
| 138 |
key: connection_kwargs[key] |
| 139 |
for key in _DISPLAYABLE_CONNECTION_KWARGS |
| 140 |
if connection_kwargs.get(key) is not None |
| 141 |
} |
| 142 |
|
| 143 |
|
| 144 |
def get_statistics(run_maintenance_tasks: bool = False) -> dict[str, list[dict[str, Any]]]: |
| 145 |
queues = [] |
| 146 |
for index, config in enumerate(get_queues_list()): |
| 147 |
queue = get_queue_by_index(index) |
| 148 |
connection = queue.connection |
| 149 |
|
| 150 |
if run_maintenance_tasks: |
| 151 |
clean_registries(queue) |
| 152 |
clean_worker_registry(queue) |
| 153 |
|
| 154 |
# Raw access to the first item from left of the redis list. |
| 155 |
# This might not be accurate since new job can be added from the left |
| 156 |
# with `at_front` parameters. |
| 157 |
# Ideally rq should supports Queue.oldest_job |
| 158 |
last_job_id = connection.lindex(queue.key, 0) |
| 159 |
last_job = queue.fetch_job(last_job_id.decode('utf-8')) if last_job_id else None |
| 160 |
if last_job: |
| 161 |
oldest_job_timestamp = to_localtime(last_job.enqueued_at).strftime('%Y-%m-%d, %H:%M:%S') |
| 162 |
else: |
| 163 |
oldest_job_timestamp = "-" |
| 164 |
|
| 165 |
connection_kwargs = get_displayable_connection_kwargs(queue) |
| 166 |
|
| 167 |
queue_data = { |
| 168 |
'name': queue.name, |
| 169 |
'jobs': queue.count, |
| 170 |
'oldest_job_timestamp': oldest_job_timestamp, |
| 171 |
'index': index, |
| 172 |
'connection_kwargs': connection_kwargs, |
| 173 |
'scheduler_pid': get_scheduler_pid(queue), |
| 174 |
} |
| 175 |
|
| 176 |
connection = get_connection(queue.name) |
| 177 |
queue_data['workers'] = Worker.count(queue=queue) |
| 178 |
|
| 179 |
finished_job_registry = FinishedJobRegistry(queue.name, connection) |
| 180 |
started_job_registry = StartedJobRegistry(queue.name, connection) |
| 181 |
deferred_job_registry = DeferredJobRegistry(queue.name, connection) |
| 182 |
failed_job_registry = FailedJobRegistry(queue.name, connection) |
| 183 |
scheduled_job_registry = ScheduledJobRegistry(queue.name, connection) |
| 184 |
queue_data['finished_jobs'] = len(finished_job_registry) |
| 185 |
queue_data['started_jobs'] = len(started_job_registry) |
| 186 |
queue_data['deferred_jobs'] = len(deferred_job_registry) |
| 187 |
queue_data['failed_jobs'] = len(failed_job_registry) |
| 188 |
queue_data['scheduled_jobs'] = len(scheduled_job_registry) |
| 189 |
|
| 190 |
queues.append(queue_data) |
| 191 |
|
| 192 |
return {'queues': queues} |
| 193 |
|
| 194 |
|
| 195 |
def get_scheduler_statistics() -> dict[str, dict[str, Any]]: |
| 196 |
schedulers = {} |
| 197 |
for index, config in enumerate(get_queues_list()): |
| 198 |
# there is only one scheduler per redis connection, so we use the connection as key |
| 199 |
# to handle the possibility of a configuration with multiple redis connections and scheduled |
| 200 |
# jobs in more than one of them |
| 201 |
queue = get_queue_by_index(index) |
| 202 |
connection_kwargs = get_displayable_connection_kwargs(queue) |
| 203 |
conn_key = ( |
| 204 |
f"{connection_kwargs.get('host', 'NOHOST')}:{connection_kwargs.get('port', 6379)}/" |
| 205 |
f"{connection_kwargs.get('db', 0)}" |
| 206 |
) |
| 207 |
if conn_key not in schedulers: |
| 208 |
try: |
| 209 |
scheduler = get_scheduler(config['name']) |
| 210 |
schedulers[conn_key] = { |
| 211 |
'count': scheduler.count(), |
| 212 |
'index': index, |
| 213 |
} |
| 214 |
except ImproperlyConfigured: |
| 215 |
pass |
| 216 |
return {'schedulers': schedulers} |
| 217 |
|
| 218 |
|
| 219 |
def get_cron_schedulers() -> list[DjangoCronScheduler]: |
| 220 |
""" |
| 221 |
Fetches all running CronScheduler instances from each unique Redis connection |
| 222 |
defined in RQ_QUEUES. |
| 223 |
|
| 224 |
Returns: |
| 225 |
List of running DjangoCronScheduler instances |
| 226 |
""" |
| 227 |
unique_configs = get_unique_connection_configs() |
| 228 |
cron_schedulers = [] |
| 229 |
|
| 230 |
for config in unique_configs: |
| 231 |
try: |
| 232 |
connection = get_redis_connection(config) |
| 233 |
# Fetch all running schedulers for this connection |
| 234 |
schedulers = DjangoCronScheduler.all(connection, cleanup=True) |
| 235 |
cron_schedulers.extend(schedulers) |
| 236 |
except Exception: |
| 237 |
# Skip configs that fail to create a connection |
| 238 |
# (e.g., USE_REDIS_CACHE without django-redis installed) |
| 239 |
pass |
| 240 |
|
| 241 |
return cron_schedulers |
| 242 |
|
| 243 |
|
| 244 |
def get_jobs( |
| 245 |
queue, |
| 246 |
job_ids, |
| 247 |
registry: Optional[ |
| 248 |
Union[ |
| 249 |
DeferredJobRegistry, |
| 250 |
FailedJobRegistry, |
| 251 |
FinishedJobRegistry, |
| 252 |
ScheduledJobRegistry, |
| 253 |
StartedJobRegistry, |
| 254 |
] |
| 255 |
] = None, |
| 256 |
) -> list[Job]: |
| 257 |
"""Fetch jobs in bulk from Redis. |
| 258 |
1. If job data is not present in Redis, discard the result |
| 259 |
2. If `registry` argument is supplied, delete empty jobs from registry |
| 260 |
""" |
| 261 |
jobs = Job.fetch_many(job_ids, connection=queue.connection, serializer=queue.serializer) |
| 262 |
valid_jobs = [] |
| 263 |
for i, job in enumerate(jobs): |
| 264 |
if job is None: |
| 265 |
if registry: |
| 266 |
registry.remove(job_ids[i]) |
| 267 |
else: |
| 268 |
valid_jobs.append(job) |
| 269 |
|
| 270 |
return valid_jobs |
| 271 |
|
| 272 |
|
| 273 |
def get_executions(queue, composite_keys: list[tuple[str, str]]) -> list[Execution]: |
| 274 |
"""Fetch executions in bulk from Redis. |
| 275 |
1. If execution data is not present in Redis, discard the result |
| 276 |
""" |
| 277 |
executions = [] |
| 278 |
for job_id, id in composite_keys: |
| 279 |
try: |
| 280 |
executions.append(Execution.fetch(id=id, job_id=job_id, connection=queue.connection)) |
| 281 |
except ValueError: |
| 282 |
pass |
| 283 |
return executions |
| 284 |
|
| 285 |
|
| 286 |
def stop_jobs(queue: Queue, job_ids: Union[str, list[str], tuple[str, ...]]) -> tuple[list[str], list[str]]: |
| 287 |
job_ids = job_ids if isinstance(job_ids, (list, tuple)) else [job_ids] |
| 288 |
stopped_job_ids = [] |
| 289 |
failed_to_stop_job_ids = [] |
| 290 |
for job_id in job_ids: |
| 291 |
try: |
| 292 |
send_stop_job_command(queue.connection, job_id) |
| 293 |
except Exception: |
| 294 |
failed_to_stop_job_ids.append(job_id) |
| 295 |
continue |
| 296 |
stopped_job_ids.append(job_id) |
| 297 |
return stopped_job_ids, failed_to_stop_job_ids |
| 298 |
|
| 299 |
|
| 300 |
def requeue_job(queue: Queue, job: Job) -> None: |
| 301 |
"""Re-enqueue a job from any source registry (failed/finished/deferred/scheduled).""" |
| 302 |
status = job.get_status(refresh=False) |
| 303 |
registry: Optional[BaseRegistry] = None |
| 304 |
if status == JobStatus.DEFERRED: |
| 305 |
registry = DeferredJobRegistry(queue.name, queue.connection) |
| 306 |
elif status == JobStatus.FINISHED: |
| 307 |
registry = FinishedJobRegistry(queue.name, queue.connection) |
| 308 |
elif status == JobStatus.SCHEDULED: |
| 309 |
registry = ScheduledJobRegistry(queue.name, queue.connection) |
| 310 |
elif status == JobStatus.FAILED: |
| 311 |
registry = FailedJobRegistry(queue.name, queue.connection) |
| 312 |
|
| 313 |
with queue.connection.pipeline() as pipeline: |
| 314 |
try: |
| 315 |
# _enqueue_job is new in RQ 1.14, this is used to enqueue |
| 316 |
# job regardless of its dependencies |
| 317 |
queue._enqueue_job(job, pipeline=pipeline) |
| 318 |
except AttributeError: |
| 319 |
queue.enqueue_job(job, pipeline=pipeline) |
| 320 |
if registry is not None: |
| 321 |
registry.remove(job, pipeline=pipeline) |
| 322 |
pipeline.execute() |
| 323 |
|
| 324 |
|
| 325 |
def reset_db_connections() -> None: |
| 326 |
for c in connections.all(): |
| 327 |
c.close() |