Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ An example configuration dictionary accepted by `extra_config`:
"QUEUES": [],

# Enable (default) or disable tracking how many jobs are currently being
# processed in each queue.
# processed in each queue, and how long the longest one has been running.
# This allows Judoscale to avoid downscaling workers that are executing jobs.
# See documentation: https://judoscale.com/docs/long-running-jobs
# NOTE: This option requires workers to have unique names. If you are running
Expand Down Expand Up @@ -433,7 +433,7 @@ An example configuration dictionary accepted by `extra_config`:
"QUEUES": [],

# Enable (default) or disable tracking how many jobs are currently being
# processed in each queue.
# processed in each queue, and how long the longest one has been running.
# This allows Judoscale to avoid downscaling workers that are executing jobs.
# See documentation: https://judoscale.com/docs/long-running-jobs
"TRACK_BUSY_JOBS": True,
Expand Down
25 changes: 20 additions & 5 deletions judoscale/celery/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,14 +234,29 @@ def _busy_metrics(self) -> List[Metric]:
return []

busy_counts = defaultdict(lambda: 0)
oldest_start_by_queue: Dict[str, float] = {}
for active_tasks in workers_tasks.values():
for task in active_tasks:
busy_counts[task["delivery_info"]["routing_key"]] += 1
queue = task["delivery_info"]["routing_key"]
busy_counts[queue] += 1
# `time_start` is unset until the pool accepts the task.
if time_start := task.get("time_start"):
oldest_start_by_queue[queue] = min(
time_start, oldest_start_by_queue.get(queue, time_start)
)

return [
Metric.for_busy_queue(queue_name=queue, busy_jobs=busy_counts[queue])
for queue in self.queues
]
metrics = []
for queue in self.queues:
metrics.append(
Metric.for_busy_queue(queue_name=queue, busy_jobs=busy_counts[queue])
)
metrics.append(
Metric.for_busy_time(
queue_name=queue,
oldest_job_start_ts=oldest_start_by_queue.get(queue),
)
)
return metrics

def collect(self) -> List[Metric]:
metrics = []
Expand Down
27 changes: 27 additions & 0 deletions judoscale/core/metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,33 @@ def for_busy_queue(cls, queue_name: str, busy_jobs: int) -> "Metric":
logger.debug(f"queue_name={queue_name}, busy_jobs={metric.value}")
return metric

@classmethod
def for_busy_time(
cls, queue_name: str, oldest_job_start_ts: Optional[float]
) -> "Metric":
"""
Calculate how long the longest-running job in a queue has been running,
log and return a Metric instance. The value is 0 when no job is running.

queue_name:
The name of the queue.

oldest_job_start_ts:
The Unix timestamp when the longest-running job started, or None.
"""
if oldest_job_start_ts is None:
metric = cls(
measurement="bt", queue_name=queue_name, value=0, timestamp=time.time()
)
else:
metric = Metric.new(
start_ms=int(oldest_job_start_ts * 1000),
queue_name=queue_name,
measurement="bt",
)
logger.debug(f"queue_name={queue_name}, busy_time={metric.value}ms")
return metric

@classmethod
def for_queue_depth(cls, queue_name: str, depth: int) -> "Metric":
"""
Expand Down
37 changes: 30 additions & 7 deletions judoscale/rq/collector.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import time
from datetime import timezone
from typing import List, Optional
from typing import List, Optional, Tuple

from redis import Redis
from rq import Queue
from rq.job import Job
from rq.utils import utcparse

from judoscale.core.config import Config
from judoscale.core.logger import logger
Expand Down Expand Up @@ -55,13 +56,29 @@ def _queue_depth(self, queue: Queue) -> Optional[int]:
)
return None

def _busy_jobs(self, queue: Queue) -> Optional[int]:
def _busy_jobs(self, queue: Queue) -> Optional[Tuple[int, Optional[float]]]:
"""
Get the number of jobs being processed for the queue, and when the
longest-running one started (a Unix timestamp, or None).
"""
# `StartedJobRegistry.count` runs `cleanup()` first, which writes to
# Redis (moving abandoned jobs to the failed registry). Count only the
# unexpired entries instead, which gives the same number read-only.
# Redis (moving abandoned jobs to the failed registry). Read only the
# unexpired entries instead, which gives the same jobs read-only.
try:
key = queue.started_job_registry.key
return int(self.redis.zcount(key, f"({time.time()}", "+inf"))
registry = queue.started_job_registry
entries = self.redis.zrangebyscore(registry.key, f"({time.time()}", "+inf")
pipeline = self.redis.pipeline()
for entry in entries:
# RQ 2 stores `<job_id>:<execution_id>` entries, RQ 1 job IDs.
job_id = entry.decode().split(":")[0]
pipeline.hget(Job.key_for(job_id), "started_at")
# RQ 1 parses to a naive datetime, though the time is in UTC.
started_ats = [
utcparse(started_at.decode()).replace(tzinfo=timezone.utc).timestamp()
for started_at in pipeline.execute()
if started_at
]
return len(entries), min(started_ats, default=None)
except Exception as e:
logger.warning(
f"Unable to get busy jobs for queue: {queue.name}", exc_info=e
Expand All @@ -80,11 +97,17 @@ def collect(self) -> List[Metric]:
for queue in queues:
if (
self.adapter_config["TRACK_BUSY_JOBS"]
and (busy_jobs := self._busy_jobs(queue)) is not None
and (busy := self._busy_jobs(queue)) is not None
):
busy_jobs, oldest_job_start_ts = busy
metrics.append(
Metric.for_busy_queue(queue_name=queue.name, busy_jobs=busy_jobs)
)
metrics.append(
Metric.for_busy_time(
queue_name=queue.name, oldest_job_start_ts=oldest_job_start_ts
)
)

if job := self.oldest_job(queue):
if job.enqueued_at is not None:
Expand Down
Loading
Loading