utils.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. from django.db import DatabaseError, connection
  2. from django.http import Http404
  3. from django.utils.translation import gettext_lazy as _
  4. from django_rq.queues import get_queue, get_queue_by_index, get_redis_connection
  5. from django_rq.settings import get_queues_list, get_queues_map
  6. from django_rq.utils import get_jobs, stop_jobs
  7. from rq import requeue_job
  8. from rq.exceptions import NoSuchJobError
  9. from rq.job import Job as RQ_Job
  10. from rq.job import JobStatus as RQJobStatus
  11. from rq.registry import (
  12. DeferredJobRegistry,
  13. FailedJobRegistry,
  14. FinishedJobRegistry,
  15. ScheduledJobRegistry,
  16. StartedJobRegistry,
  17. )
  18. __all__ = (
  19. 'delete_rq_job',
  20. 'enqueue_rq_job',
  21. 'get_db_schema',
  22. 'get_rq_jobs',
  23. 'get_rq_jobs_from_status',
  24. 'requeue_rq_job',
  25. 'stop_rq_job',
  26. )
  27. def get_rq_jobs():
  28. """
  29. Return a list of all RQ jobs.
  30. """
  31. jobs = set()
  32. for queue in get_queues_list():
  33. queue = get_queue(queue['name'])
  34. jobs.update(queue.get_jobs())
  35. return list(jobs)
  36. def get_rq_jobs_from_status(queue, status):
  37. """
  38. Return the RQ jobs with the given status.
  39. """
  40. jobs = []
  41. try:
  42. registry_cls = {
  43. RQJobStatus.STARTED: StartedJobRegistry,
  44. RQJobStatus.DEFERRED: DeferredJobRegistry,
  45. RQJobStatus.FINISHED: FinishedJobRegistry,
  46. RQJobStatus.FAILED: FailedJobRegistry,
  47. RQJobStatus.SCHEDULED: ScheduledJobRegistry,
  48. }[status]
  49. except KeyError:
  50. raise Http404
  51. registry = registry_cls(queue.name, queue.connection)
  52. job_ids = registry.get_job_ids()
  53. if status != RQJobStatus.DEFERRED:
  54. jobs = get_jobs(queue, job_ids, registry)
  55. else:
  56. # Deferred jobs require special handling
  57. for job_id in job_ids:
  58. try:
  59. jobs.append(RQ_Job.fetch(job_id, connection=queue.connection, serializer=queue.serializer))
  60. except NoSuchJobError:
  61. pass
  62. if jobs and status == RQJobStatus.SCHEDULED:
  63. for job in jobs:
  64. job.scheduled_at = registry.get_scheduled_time(job)
  65. return jobs
  66. def delete_rq_job(job_id):
  67. """
  68. Delete the specified RQ job.
  69. """
  70. config = get_queues_list()[0]
  71. try:
  72. job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
  73. except NoSuchJobError:
  74. raise Http404(_("Job {job_id} not found").format(job_id=job_id))
  75. queue_index = get_queues_map()[job.origin]
  76. queue = get_queue_by_index(queue_index)
  77. # Remove job id from queue and delete the actual job
  78. queue.connection.lrem(queue.key, 0, job.id)
  79. job.delete()
  80. def requeue_rq_job(job_id):
  81. """
  82. Requeue the specified RQ job.
  83. """
  84. config = get_queues_list()[0]
  85. try:
  86. job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
  87. except NoSuchJobError:
  88. raise Http404(_("Job {id} not found.").format(id=job_id))
  89. queue_index = get_queues_map()[job.origin]
  90. queue = get_queue_by_index(queue_index)
  91. requeue_job(job_id, connection=queue.connection, serializer=queue.serializer)
  92. def enqueue_rq_job(job_id):
  93. """
  94. Enqueue the specified RQ job.
  95. """
  96. config = get_queues_list()[0]
  97. try:
  98. job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
  99. except NoSuchJobError:
  100. raise Http404(_("Job {id} not found.").format(id=job_id))
  101. queue_index = get_queues_map()[job.origin]
  102. queue = get_queue_by_index(queue_index)
  103. try:
  104. # _enqueue_job is new in RQ 1.14, this is used to enqueue
  105. # job regardless of its dependencies
  106. queue._enqueue_job(job)
  107. except AttributeError:
  108. queue.enqueue_job(job)
  109. # Remove job from correct registry if needed
  110. if job.get_status() == RQJobStatus.DEFERRED:
  111. registry = DeferredJobRegistry(queue.name, queue.connection)
  112. registry.remove(job)
  113. elif job.get_status() == RQJobStatus.FINISHED:
  114. registry = FinishedJobRegistry(queue.name, queue.connection)
  115. registry.remove(job)
  116. elif job.get_status() == RQJobStatus.SCHEDULED:
  117. registry = ScheduledJobRegistry(queue.name, queue.connection)
  118. registry.remove(job)
  119. def stop_rq_job(job_id):
  120. """
  121. Stop the specified RQ job.
  122. """
  123. config = get_queues_list()[0]
  124. try:
  125. job = RQ_Job.fetch(job_id, connection=get_redis_connection(config['connection_config']),)
  126. except NoSuchJobError:
  127. raise Http404(_("Job {job_id} not found").format(job_id=job_id))
  128. queue_index = get_queues_map()[job.origin]
  129. queue = get_queue_by_index(queue_index)
  130. return stop_jobs(queue, job_id)[0]
  131. def get_db_schema():
  132. """
  133. Query the current PostgreSQL schema and return a list of tables, each with its columns and
  134. indexes. Returns an empty list if the database is not accessible.
  135. """
  136. db_schema = []
  137. try:
  138. with connection.cursor() as cursor:
  139. cursor.execute("""
  140. SELECT table_name, column_name, data_type, is_nullable, column_default
  141. FROM information_schema.columns
  142. WHERE table_schema = current_schema()
  143. ORDER BY table_name, ordinal_position
  144. """)
  145. columns_by_table = {}
  146. for table_name, column_name, data_type, is_nullable, column_default in cursor.fetchall():
  147. columns_by_table.setdefault(table_name, []).append({
  148. 'name': column_name,
  149. 'type': data_type,
  150. 'nullable': is_nullable == 'YES',
  151. 'default': column_default,
  152. })
  153. cursor.execute("""
  154. SELECT tablename, indexname, indexdef
  155. FROM pg_indexes
  156. WHERE schemaname = current_schema()
  157. ORDER BY tablename, indexname
  158. """)
  159. indexes_by_table = {}
  160. for table_name, index_name, index_def in cursor.fetchall():
  161. indexes_by_table.setdefault(table_name, []).append({
  162. 'name': index_name,
  163. 'definition': index_def,
  164. })
  165. for table_name in sorted(columns_by_table.keys()):
  166. db_schema.append({
  167. 'name': table_name,
  168. 'columns': columns_by_table[table_name],
  169. 'indexes': indexes_by_table.get(table_name, []),
  170. })
  171. except DatabaseError:
  172. pass
  173. return db_schema