Debian Codegraph @

django_rq/cron_views.py

raw
1 from typing import Any
2
3 from django.contrib.admin.views.decorators import staff_member_required
4 from django.http import Http404, HttpRequest, HttpResponse
5 from django.shortcuts import render
6 from django.views.decorators.cache import never_cache
7 from rq.job import Job
8
9 from .connection_utils import get_connection_by_index
10 from .cron import (
11 CRON_JOB_HISTORY_SUPPORTED,
12 DjangoCronScheduler,
13 get_cron_job_data,
14 get_cron_job_history,
15 get_cron_job_history_count,
16 )
17 from .queues import get_queue_by_index
18 from .utils import get_displayable_connection_kwargs, paginate
19 from .views import each_context
20
21 ITEMS_PER_PAGE = 20
22
23
24 def get_scheduler(connection_index: int, scheduler_name: str) -> DjangoCronScheduler:
25 """
26 Returns the cron scheduler with the given name on the given connection.
27
28 Raises:
29 Http404: If the connection index is invalid or the scheduler is not found
30 """
31 try:
32 connection = get_connection_by_index(connection_index)
33 except (IndexError, ValueError):
34 raise Http404("Invalid connection index")
35
36 for scheduler in DjangoCronScheduler.all(connection, cleanup=True):
37 if scheduler.name == scheduler_name:
38 return scheduler
39
40 raise Http404(f"Scheduler '{scheduler_name}' not found")
41
42
43 @never_cache
44 @staff_member_required
45 def cron_scheduler_detail(request: HttpRequest, connection_index: int, scheduler_name: str) -> HttpResponse:
46 """
47 Display details for a specific cron scheduler.
48
49 Args:
50 request: Django request object
51 connection_index: Index of the Redis connection
52 scheduler_name: Name of the cron scheduler
53
54 Raises:
55 Http404: If the scheduler is not found
56 """
57 scheduler = get_scheduler(connection_index, scheduler_name)
58
59 context_data = {
60 **each_context(request),
61 "scheduler": scheduler,
62 "connection_index": connection_index,
63 "connection_kwargs": get_displayable_connection_kwargs(scheduler),
64 "cron_jobs": scheduler.get_jobs_data(),
65 "job_history_supported": CRON_JOB_HISTORY_SUPPORTED,
66 }
67
68 return render(request, 'django_rq/cron_scheduler_detail.html', context_data)
69
70
71 @never_cache
72 @staff_member_required
73 def cron_job_detail(
74 request: HttpRequest, connection_index: int, scheduler_name: str, cron_job_name: str
75 ) -> HttpResponse:
76 """
77 Display a cron job along with the jobs it has spawned.
78
79 Args:
80 request: Django request object
81 connection_index: Index of the Redis connection
82 scheduler_name: Name of the cron scheduler
83 cron_job_name: Name of the cron job, which defaults to the function's import path
84
85 Raises:
86 Http404: If the scheduler or the cron job is not found
87 """
88 scheduler = get_scheduler(connection_index, scheduler_name)
89
90 cron_job = None
91 for job in scheduler.get_jobs():
92 if (getattr(job, 'name', None) or job.func_name) == cron_job_name:
93 cron_job = job
94 break
95
96 if cron_job is None:
97 raise Http404(f"Cron job '{cron_job_name}' not found in scheduler '{scheduler_name}'")
98
99 cron_job_data = get_cron_job_data(cron_job)
100 queue_index = cron_job_data['queue_index']
101
102 # Jobs are fetched with their queue's serializer. When the queue is no longer in RQ_QUEUES
103 # we can still list the history, using the scheduler's connection and the default serializer.
104 if queue_index is not None:
105 queue = get_queue_by_index(queue_index)
106 connection, serializer = queue.connection, queue.serializer
107 else:
108 connection, serializer = scheduler.connection, None
109
110 num_jobs = get_cron_job_history_count(cron_job, scheduler.connection)
111 page, page_range, offset = paginate(request, num_jobs, ITEMS_PER_PAGE)
112
113 history: list[dict[str, Any]] = []
114
115 if num_jobs > 0:
116 entries = get_cron_job_history(cron_job, scheduler.connection, offset, offset + ITEMS_PER_PAGE - 1)
117
118 # A job's data is deleted when its result_ttl expires, long before its history entry
119 # goes away, so a missing job is the norm rather than an error. Keep the row and show
120 # what the history itself knows: the job's ID and when it was enqueued.
121 jobs = Job.fetch_many([job_id for job_id, _ in entries], connection=connection, serializer=serializer)
122 history = [
123 {'job_id': job_id, 'enqueued_at': enqueued_at, 'job': job}
124 for (job_id, enqueued_at), job in zip(entries, jobs)
125 ]
126
127 context_data = {
128 **each_context(request),
129 'scheduler': scheduler,
130 'connection_index': connection_index,
131 'cron_job': cron_job_data,
132 'queue_index': queue_index,
133 'history': history,
134 'num_jobs': num_jobs,
135 'page': page,
136 'page_range': page_range,
137 'job_history_supported': CRON_JOB_HISTORY_SUPPORTED,
138 }
139
140 return render(request, 'django_rq/cron_job_detail.html', context_data)