subscription_state.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. from __future__ import absolute_import
  2. import abc
  3. import logging
  4. import re
  5. from kafka.vendor import six
  6. from kafka.errors import IllegalStateError
  7. from kafka.protocol.offset import OffsetResetStrategy
  8. from kafka.structs import OffsetAndMetadata
  9. log = logging.getLogger(__name__)
  10. class SubscriptionState(object):
  11. """
  12. A class for tracking the topics, partitions, and offsets for the consumer.
  13. A partition is "assigned" either directly with assign_from_user() (manual
  14. assignment) or with assign_from_subscribed() (automatic assignment from
  15. subscription).
  16. Once assigned, the partition is not considered "fetchable" until its initial
  17. position has been set with seek(). Fetchable partitions track a fetch
  18. position which is used to set the offset of the next fetch, and a consumed
  19. position which is the last offset that has been returned to the user. You
  20. can suspend fetching from a partition through pause() without affecting the
  21. fetched/consumed offsets. The partition will remain unfetchable until the
  22. resume() is used. You can also query the pause state independently with
  23. is_paused().
  24. Note that pause state as well as fetch/consumed positions are not preserved
  25. when partition assignment is changed whether directly by the user or
  26. through a group rebalance.
  27. This class also maintains a cache of the latest commit position for each of
  28. the assigned partitions. This is updated through committed() and can be used
  29. to set the initial fetch position (e.g. Fetcher._reset_offset() ).
  30. """
  31. _SUBSCRIPTION_EXCEPTION_MESSAGE = (
  32. "You must choose only one way to configure your consumer:"
  33. " (1) subscribe to specific topics by name,"
  34. " (2) subscribe to topics matching a regex pattern,"
  35. " (3) assign itself specific topic-partitions.")
  36. # Taken from: https://github.com/apache/kafka/blob/39eb31feaeebfb184d98cc5d94da9148c2319d81/clients/src/main/java/org/apache/kafka/common/internals/Topic.java#L29
  37. _MAX_NAME_LENGTH = 249
  38. _TOPIC_LEGAL_CHARS = re.compile('^[a-zA-Z0-9._-]+$')
  39. def __init__(self, offset_reset_strategy='earliest'):
  40. """Initialize a SubscriptionState instance
  41. Keyword Arguments:
  42. offset_reset_strategy: 'earliest' or 'latest', otherwise
  43. exception will be raised when fetching an offset that is no
  44. longer available. Default: 'earliest'
  45. """
  46. try:
  47. offset_reset_strategy = getattr(OffsetResetStrategy,
  48. offset_reset_strategy.upper())
  49. except AttributeError:
  50. log.warning('Unrecognized offset_reset_strategy, using NONE')
  51. offset_reset_strategy = OffsetResetStrategy.NONE
  52. self._default_offset_reset_strategy = offset_reset_strategy
  53. self.subscription = None # set() or None
  54. self.subscribed_pattern = None # regex str or None
  55. self._group_subscription = set()
  56. self._user_assignment = set()
  57. self.assignment = dict()
  58. self.needs_partition_assignment = False
  59. self.listener = None
  60. # initialize to true for the consumers to fetch offset upon starting up
  61. self.needs_fetch_committed_offsets = True
  62. def subscribe(self, topics=(), pattern=None, listener=None):
  63. """Subscribe to a list of topics, or a topic regex pattern.
  64. Partitions will be dynamically assigned via a group coordinator.
  65. Topic subscriptions are not incremental: this list will replace the
  66. current assignment (if there is one).
  67. This method is incompatible with assign_from_user()
  68. Arguments:
  69. topics (list): List of topics for subscription.
  70. pattern (str): Pattern to match available topics. You must provide
  71. either topics or pattern, but not both.
  72. listener (ConsumerRebalanceListener): Optionally include listener
  73. callback, which will be called before and after each rebalance
  74. operation.
  75. As part of group management, the consumer will keep track of the
  76. list of consumers that belong to a particular group and will
  77. trigger a rebalance operation if one of the following events
  78. trigger:
  79. * Number of partitions change for any of the subscribed topics
  80. * Topic is created or deleted
  81. * An existing member of the consumer group dies
  82. * A new member is added to the consumer group
  83. When any of these events are triggered, the provided listener
  84. will be invoked first to indicate that the consumer's assignment
  85. has been revoked, and then again when the new assignment has
  86. been received. Note that this listener will immediately override
  87. any listener set in a previous call to subscribe. It is
  88. guaranteed, however, that the partitions revoked/assigned
  89. through this interface are from topics subscribed in this call.
  90. """
  91. if self._user_assignment or (topics and pattern):
  92. raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
  93. assert topics or pattern, 'Must provide topics or pattern'
  94. if pattern:
  95. log.info('Subscribing to pattern: /%s/', pattern)
  96. self.subscription = set()
  97. self.subscribed_pattern = re.compile(pattern)
  98. else:
  99. self.change_subscription(topics)
  100. if listener and not isinstance(listener, ConsumerRebalanceListener):
  101. raise TypeError('listener must be a ConsumerRebalanceListener')
  102. self.listener = listener
  103. def _ensure_valid_topic_name(self, topic):
  104. """ Ensures that the topic name is valid according to the kafka source. """
  105. # See Kafka Source:
  106. # https://github.com/apache/kafka/blob/39eb31feaeebfb184d98cc5d94da9148c2319d81/clients/src/main/java/org/apache/kafka/common/internals/Topic.java
  107. if topic is None:
  108. raise TypeError('All topics must not be None')
  109. if not isinstance(topic, six.string_types):
  110. raise TypeError('All topics must be strings')
  111. if len(topic) == 0:
  112. raise ValueError('All topics must be non-empty strings')
  113. if topic == '.' or topic == '..':
  114. raise ValueError('Topic name cannot be "." or ".."')
  115. if len(topic) > self._MAX_NAME_LENGTH:
  116. raise ValueError('Topic name is illegal, it can\'t be longer than {0} characters, topic: "{1}"'.format(self._MAX_NAME_LENGTH, topic))
  117. if not self._TOPIC_LEGAL_CHARS.match(topic):
  118. raise ValueError('Topic name "{0}" is illegal, it contains a character other than ASCII alphanumerics, ".", "_" and "-"'.format(topic))
  119. def change_subscription(self, topics):
  120. """Change the topic subscription.
  121. Arguments:
  122. topics (list of str): topics for subscription
  123. Raises:
  124. IllegalStateErrror: if assign_from_user has been used already
  125. TypeError: if a topic is None or a non-str
  126. ValueError: if a topic is an empty string or
  127. - a topic name is '.' or '..' or
  128. - a topic name does not consist of ASCII-characters/'-'/'_'/'.'
  129. """
  130. if self._user_assignment:
  131. raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
  132. if isinstance(topics, six.string_types):
  133. topics = [topics]
  134. if self.subscription == set(topics):
  135. log.warning("subscription unchanged by change_subscription(%s)",
  136. topics)
  137. return
  138. for t in topics:
  139. self._ensure_valid_topic_name(t)
  140. log.info('Updating subscribed topics to: %s', topics)
  141. self.subscription = set(topics)
  142. self._group_subscription.update(topics)
  143. self.needs_partition_assignment = True
  144. # Remove any assigned partitions which are no longer subscribed to
  145. for tp in set(self.assignment.keys()):
  146. if tp.topic not in self.subscription:
  147. del self.assignment[tp]
  148. def group_subscribe(self, topics):
  149. """Add topics to the current group subscription.
  150. This is used by the group leader to ensure that it receives metadata
  151. updates for all topics that any member of the group is subscribed to.
  152. Arguments:
  153. topics (list of str): topics to add to the group subscription
  154. """
  155. if self._user_assignment:
  156. raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
  157. self._group_subscription.update(topics)
  158. def mark_for_reassignment(self):
  159. if self._user_assignment:
  160. raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
  161. assert self.subscription is not None, 'Subscription required'
  162. self._group_subscription.intersection_update(self.subscription)
  163. self.needs_partition_assignment = True
  164. def assign_from_user(self, partitions):
  165. """Manually assign a list of TopicPartitions to this consumer.
  166. This interface does not allow for incremental assignment and will
  167. replace the previous assignment (if there was one).
  168. Manual topic assignment through this method does not use the consumer's
  169. group management functionality. As such, there will be no rebalance
  170. operation triggered when group membership or cluster and topic metadata
  171. change. Note that it is not possible to use both manual partition
  172. assignment with assign() and group assignment with subscribe().
  173. Arguments:
  174. partitions (list of TopicPartition): assignment for this instance.
  175. Raises:
  176. IllegalStateError: if consumer has already called subscribe()
  177. """
  178. if self.subscription is not None:
  179. raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
  180. self._user_assignment.clear()
  181. self._user_assignment.update(partitions)
  182. for partition in partitions:
  183. if partition not in self.assignment:
  184. self._add_assigned_partition(partition)
  185. for tp in set(self.assignment.keys()) - self._user_assignment:
  186. del self.assignment[tp]
  187. self.needs_partition_assignment = False
  188. self.needs_fetch_committed_offsets = True
  189. def assign_from_subscribed(self, assignments):
  190. """Update the assignment to the specified partitions
  191. This method is called by the coordinator to dynamically assign
  192. partitions based on the consumer's topic subscription. This is different
  193. from assign_from_user() which directly sets the assignment from a
  194. user-supplied TopicPartition list.
  195. Arguments:
  196. assignments (list of TopicPartition): partitions to assign to this
  197. consumer instance.
  198. """
  199. if self.subscription is None:
  200. raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
  201. for tp in assignments:
  202. if tp.topic not in self.subscription:
  203. raise ValueError("Assigned partition %s for non-subscribed topic." % str(tp))
  204. self.assignment.clear()
  205. for tp in assignments:
  206. self._add_assigned_partition(tp)
  207. self.needs_partition_assignment = False
  208. log.info("Updated partition assignment: %s", assignments)
  209. def unsubscribe(self):
  210. """Clear all topic subscriptions and partition assignments"""
  211. self.subscription = None
  212. self._user_assignment.clear()
  213. self.assignment.clear()
  214. self.needs_partition_assignment = True
  215. self.subscribed_pattern = None
  216. def group_subscription(self):
  217. """Get the topic subscription for the group.
  218. For the leader, this will include the union of all member subscriptions.
  219. For followers, it is the member's subscription only.
  220. This is used when querying topic metadata to detect metadata changes
  221. that would require rebalancing (the leader fetches metadata for all
  222. topics in the group so that it can do partition assignment).
  223. Returns:
  224. set: topics
  225. """
  226. return self._group_subscription
  227. def seek(self, partition, offset):
  228. """Manually specify the fetch offset for a TopicPartition.
  229. Overrides the fetch offsets that the consumer will use on the next
  230. poll(). If this API is invoked for the same partition more than once,
  231. the latest offset will be used on the next poll(). Note that you may
  232. lose data if this API is arbitrarily used in the middle of consumption,
  233. to reset the fetch offsets.
  234. Arguments:
  235. partition (TopicPartition): partition for seek operation
  236. offset (int): message offset in partition
  237. """
  238. self.assignment[partition].seek(offset)
  239. def assigned_partitions(self):
  240. """Return set of TopicPartitions in current assignment."""
  241. return set(self.assignment.keys())
  242. def paused_partitions(self):
  243. """Return current set of paused TopicPartitions."""
  244. return set(partition for partition in self.assignment
  245. if self.is_paused(partition))
  246. def fetchable_partitions(self):
  247. """Return set of TopicPartitions that should be Fetched."""
  248. fetchable = set()
  249. for partition, state in six.iteritems(self.assignment):
  250. if state.is_fetchable():
  251. fetchable.add(partition)
  252. return fetchable
  253. def partitions_auto_assigned(self):
  254. """Return True unless user supplied partitions manually."""
  255. return self.subscription is not None
  256. def all_consumed_offsets(self):
  257. """Returns consumed offsets as {TopicPartition: OffsetAndMetadata}"""
  258. all_consumed = {}
  259. for partition, state in six.iteritems(self.assignment):
  260. if state.has_valid_position:
  261. all_consumed[partition] = OffsetAndMetadata(state.position, '')
  262. return all_consumed
  263. def need_offset_reset(self, partition, offset_reset_strategy=None):
  264. """Mark partition for offset reset using specified or default strategy.
  265. Arguments:
  266. partition (TopicPartition): partition to mark
  267. offset_reset_strategy (OffsetResetStrategy, optional)
  268. """
  269. if offset_reset_strategy is None:
  270. offset_reset_strategy = self._default_offset_reset_strategy
  271. self.assignment[partition].await_reset(offset_reset_strategy)
  272. def has_default_offset_reset_policy(self):
  273. """Return True if default offset reset policy is Earliest or Latest"""
  274. return self._default_offset_reset_strategy != OffsetResetStrategy.NONE
  275. def is_offset_reset_needed(self, partition):
  276. return self.assignment[partition].awaiting_reset
  277. def has_all_fetch_positions(self):
  278. for state in self.assignment.values():
  279. if not state.has_valid_position:
  280. return False
  281. return True
  282. def missing_fetch_positions(self):
  283. missing = set()
  284. for partition, state in six.iteritems(self.assignment):
  285. if not state.has_valid_position:
  286. missing.add(partition)
  287. return missing
  288. def is_assigned(self, partition):
  289. return partition in self.assignment
  290. def is_paused(self, partition):
  291. return partition in self.assignment and self.assignment[partition].paused
  292. def is_fetchable(self, partition):
  293. return partition in self.assignment and self.assignment[partition].is_fetchable()
  294. def pause(self, partition):
  295. self.assignment[partition].pause()
  296. def resume(self, partition):
  297. self.assignment[partition].resume()
  298. def _add_assigned_partition(self, partition):
  299. self.assignment[partition] = TopicPartitionState()
  300. class TopicPartitionState(object):
  301. def __init__(self):
  302. self.committed = None # last committed position
  303. self.has_valid_position = False # whether we have valid position
  304. self.paused = False # whether this partition has been paused by the user
  305. self.awaiting_reset = False # whether we are awaiting reset
  306. self.reset_strategy = None # the reset strategy if awaitingReset is set
  307. self._position = None # offset exposed to the user
  308. self.highwater = None
  309. self.drop_pending_message_set = False
  310. def _set_position(self, offset):
  311. assert self.has_valid_position, 'Valid position required'
  312. self._position = offset
  313. def _get_position(self):
  314. return self._position
  315. position = property(_get_position, _set_position, None, "last position")
  316. def await_reset(self, strategy):
  317. self.awaiting_reset = True
  318. self.reset_strategy = strategy
  319. self._position = None
  320. self.has_valid_position = False
  321. def seek(self, offset):
  322. self._position = offset
  323. self.awaiting_reset = False
  324. self.reset_strategy = None
  325. self.has_valid_position = True
  326. self.drop_pending_message_set = True
  327. def pause(self):
  328. self.paused = True
  329. def resume(self):
  330. self.paused = False
  331. def is_fetchable(self):
  332. return not self.paused and self.has_valid_position
  333. class ConsumerRebalanceListener(object):
  334. """
  335. A callback interface that the user can implement to trigger custom actions
  336. when the set of partitions assigned to the consumer changes.
  337. This is applicable when the consumer is having Kafka auto-manage group
  338. membership. If the consumer's directly assign partitions, those
  339. partitions will never be reassigned and this callback is not applicable.
  340. When Kafka is managing the group membership, a partition re-assignment will
  341. be triggered any time the members of the group changes or the subscription
  342. of the members changes. This can occur when processes die, new process
  343. instances are added or old instances come back to life after failure.
  344. Rebalances can also be triggered by changes affecting the subscribed
  345. topics (e.g. when then number of partitions is administratively adjusted).
  346. There are many uses for this functionality. One common use is saving offsets
  347. in a custom store. By saving offsets in the on_partitions_revoked(), call we
  348. can ensure that any time partition assignment changes the offset gets saved.
  349. Another use is flushing out any kind of cache of intermediate results the
  350. consumer may be keeping. For example, consider a case where the consumer is
  351. subscribed to a topic containing user page views, and the goal is to count
  352. the number of page views per users for each five minute window. Let's say
  353. the topic is partitioned by the user id so that all events for a particular
  354. user will go to a single consumer instance. The consumer can keep in memory
  355. a running tally of actions per user and only flush these out to a remote
  356. data store when its cache gets too big. However if a partition is reassigned
  357. it may want to automatically trigger a flush of this cache, before the new
  358. owner takes over consumption.
  359. This callback will execute in the user thread as part of the Consumer.poll()
  360. whenever partition assignment changes.
  361. It is guaranteed that all consumer processes will invoke
  362. on_partitions_revoked() prior to any process invoking
  363. on_partitions_assigned(). So if offsets or other state is saved in the
  364. on_partitions_revoked() call, it should be saved by the time the process
  365. taking over that partition has their on_partitions_assigned() callback
  366. called to load the state.
  367. """
  368. __metaclass__ = abc.ABCMeta
  369. @abc.abstractmethod
  370. def on_partitions_revoked(self, revoked):
  371. """
  372. A callback method the user can implement to provide handling of offset
  373. commits to a customized store on the start of a rebalance operation.
  374. This method will be called before a rebalance operation starts and
  375. after the consumer stops fetching data. It is recommended that offsets
  376. should be committed in this callback to either Kafka or a custom offset
  377. store to prevent duplicate data.
  378. NOTE: This method is only called before rebalances. It is not called
  379. prior to KafkaConsumer.close()
  380. Arguments:
  381. revoked (list of TopicPartition): the partitions that were assigned
  382. to the consumer on the last rebalance
  383. """
  384. pass
  385. @abc.abstractmethod
  386. def on_partitions_assigned(self, assigned):
  387. """
  388. A callback method the user can implement to provide handling of
  389. customized offsets on completion of a successful partition
  390. re-assignment. This method will be called after an offset re-assignment
  391. completes and before the consumer starts fetching data.
  392. It is guaranteed that all the processes in a consumer group will execute
  393. their on_partitions_revoked() callback before any instance executes its
  394. on_partitions_assigned() callback.
  395. Arguments:
  396. assigned (list of TopicPartition): the partitions assigned to the
  397. consumer (may include partitions that were previously assigned)
  398. """
  399. pass