Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

230 řádky
8.1 KiB

  1. from .compat import as_text
  2. from .connections import resolve_connection
  3. from .defaults import DEFAULT_FAILURE_TTL
  4. from .exceptions import InvalidJobOperation, NoSuchJobError
  5. from .job import Job, JobStatus
  6. from .queue import Queue
  7. from .utils import backend_class, current_timestamp
  8. class BaseRegistry(object):
  9. """
  10. Base implementation of a job registry, implemented in Redis sorted set.
  11. Each job is stored as a key in the registry, scored by expiration time
  12. (unix timestamp).
  13. """
  14. job_class = Job
  15. key_template = 'rq:registry:{0}'
  16. def __init__(self, name='default', connection=None, job_class=None,
  17. queue=None):
  18. if queue:
  19. self.name = queue.name
  20. self.connection = resolve_connection(queue.connection)
  21. else:
  22. self.name = name
  23. self.connection = resolve_connection(connection)
  24. self.key = self.key_template.format(self.name)
  25. self.job_class = backend_class(self, 'job_class', override=job_class)
  26. def __len__(self):
  27. """Returns the number of jobs in this registry"""
  28. return self.count
  29. def __contains__(self, item):
  30. """
  31. Returns a boolean indicating registry contains the given
  32. job instance or job id.
  33. """
  34. job_id = item
  35. if isinstance(item, self.job_class):
  36. job_id = item.id
  37. return self.connection.zscore(self.key, job_id) is not None
  38. @property
  39. def count(self):
  40. """Returns the number of jobs in this registry"""
  41. self.cleanup()
  42. return self.connection.zcard(self.key)
  43. def add(self, job, ttl=0, pipeline=None):
  44. """Adds a job to a registry with expiry time of now + ttl, unless it's -1 which is set to +inf"""
  45. score = ttl if ttl < 0 else current_timestamp() + ttl
  46. if score == -1:
  47. score = '+inf'
  48. if pipeline is not None:
  49. return pipeline.zadd(self.key, {job.id: score})
  50. return self.connection.zadd(self.key, {job.id: score})
  51. def remove(self, job, pipeline=None):
  52. connection = pipeline if pipeline is not None else self.connection
  53. return connection.zrem(self.key, job.id)
  54. def get_expired_job_ids(self, timestamp=None):
  55. """Returns job ids whose score are less than current timestamp.
  56. Returns ids for jobs with an expiry time earlier than timestamp,
  57. specified as seconds since the Unix epoch. timestamp defaults to call
  58. time if unspecified.
  59. """
  60. score = timestamp if timestamp is not None else current_timestamp()
  61. return [as_text(job_id) for job_id in
  62. self.connection.zrangebyscore(self.key, 0, score)]
  63. def get_job_ids(self, start=0, end=-1):
  64. """Returns list of all job ids."""
  65. self.cleanup()
  66. return [as_text(job_id) for job_id in
  67. self.connection.zrange(self.key, start, end)]
  68. def get_queue(self):
  69. """Returns Queue object associated with this registry."""
  70. return Queue(self.name, connection=self.connection)
  71. class StartedJobRegistry(BaseRegistry):
  72. """
  73. Registry of currently executing jobs. Each queue maintains a
  74. StartedJobRegistry. Jobs in this registry are ones that are currently
  75. being executed.
  76. Jobs are added to registry right before they are executed and removed
  77. right after completion (success or failure).
  78. """
  79. key_template = 'rq:wip:{0}'
  80. def cleanup(self, timestamp=None):
  81. """Remove expired jobs from registry and add them to FailedJobRegistry.
  82. Removes jobs with an expiry time earlier than timestamp, specified as
  83. seconds since the Unix epoch. timestamp defaults to call time if
  84. unspecified. Removed jobs are added to the global failed job queue.
  85. """
  86. score = timestamp if timestamp is not None else current_timestamp()
  87. job_ids = self.get_expired_job_ids(score)
  88. if job_ids:
  89. failed_job_registry = FailedJobRegistry(self.name, self.connection)
  90. with self.connection.pipeline() as pipeline:
  91. for job_id in job_ids:
  92. try:
  93. job = self.job_class.fetch(job_id,
  94. connection=self.connection)
  95. job.set_status(JobStatus.FAILED)
  96. job.save(pipeline=pipeline, include_meta=False)
  97. job.cleanup(ttl=-1, pipeline=pipeline)
  98. failed_job_registry.add(job, job.failure_ttl)
  99. except NoSuchJobError:
  100. pass
  101. pipeline.zremrangebyscore(self.key, 0, score)
  102. pipeline.execute()
  103. return job_ids
  104. class FinishedJobRegistry(BaseRegistry):
  105. """
  106. Registry of jobs that have been completed. Jobs are added to this
  107. registry after they have successfully completed for monitoring purposes.
  108. """
  109. key_template = 'rq:finished:{0}'
  110. def cleanup(self, timestamp=None):
  111. """Remove expired jobs from registry.
  112. Removes jobs with an expiry time earlier than timestamp, specified as
  113. seconds since the Unix epoch. timestamp defaults to call time if
  114. unspecified.
  115. """
  116. score = timestamp if timestamp is not None else current_timestamp()
  117. self.connection.zremrangebyscore(self.key, 0, score)
  118. class FailedJobRegistry(BaseRegistry):
  119. """
  120. Registry of containing failed jobs.
  121. """
  122. key_template = 'rq:failed:{0}'
  123. def cleanup(self, timestamp=None):
  124. """Remove expired jobs from registry.
  125. Removes jobs with an expiry time earlier than timestamp, specified as
  126. seconds since the Unix epoch. timestamp defaults to call time if
  127. unspecified.
  128. """
  129. score = timestamp if timestamp is not None else current_timestamp()
  130. self.connection.zremrangebyscore(self.key, 0, score)
  131. def add(self, job, ttl=None, exc_string='', pipeline=None):
  132. """
  133. Adds a job to a registry with expiry time of now + ttl.
  134. `ttl` defaults to DEFAULT_FAILURE_TTL if not specified.
  135. """
  136. if ttl is None:
  137. ttl = DEFAULT_FAILURE_TTL
  138. score = ttl if ttl < 0 else current_timestamp() + ttl
  139. if pipeline:
  140. p = pipeline
  141. else:
  142. p = self.connection.pipeline()
  143. job.exc_info = exc_string
  144. job.save(pipeline=p, include_meta=False)
  145. job.cleanup(ttl=-1, pipeline=p) # failed job won't expire
  146. p.zadd(self.key, {job.id: score})
  147. if not pipeline:
  148. p.execute()
  149. def requeue(self, job_or_id):
  150. """Requeues the job with the given job ID."""
  151. if isinstance(job_or_id, self.job_class):
  152. job = job_or_id
  153. else:
  154. job = self.job_class.fetch(job_or_id, connection=self.connection)
  155. result = self.connection.zrem(self.key, job.id)
  156. if not result:
  157. raise InvalidJobOperation
  158. queue = Queue(job.origin, connection=self.connection,
  159. job_class=self.job_class)
  160. return queue.enqueue_job(job)
  161. class DeferredJobRegistry(BaseRegistry):
  162. """
  163. Registry of deferred jobs (waiting for another job to finish).
  164. """
  165. key_template = 'rq:deferred:{0}'
  166. def cleanup(self):
  167. """This method is only here to prevent errors because this method is
  168. automatically called by `count()` and `get_job_ids()` methods
  169. implemented in BaseRegistry."""
  170. pass
  171. def clean_registries(queue):
  172. """Cleans StartedJobRegistry and FinishedJobRegistry of a queue."""
  173. registry = FinishedJobRegistry(name=queue.name,
  174. connection=queue.connection,
  175. job_class=queue.job_class)
  176. registry.cleanup()
  177. registry = StartedJobRegistry(name=queue.name,
  178. connection=queue.connection,
  179. job_class=queue.job_class)
  180. registry.cleanup()
  181. registry = FailedJobRegistry(name=queue.name,
  182. connection=queue.connection,
  183. job_class=queue.job_class)
  184. registry.cleanup()