├── .gitignore ├── LICENSE.txt ├── README.md ├── disruptor ├── __init__.py └── disruptor.py ├── setup.py └── tests ├── __init__.py └── test_disruptor.py /.gitignore: -------------------------------------------------------------------------------- 1 | **/*.pyc 2 | **/__pycache__ 3 | .vscode -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # py-disruptor 2 | 3 | A **basic**, **unoptimized** multi-threaded RingBuffer - a "[Disruptor](https://lmax-exchange.github.io/disruptor/)-Lite" implementation using a thread-per-consumer model with python threads. 4 | 5 | Works with both python2 and python3, does not support gated consumers. 6 | 7 | Generally useful for parallelizable io-bound tasks, such as updating a database. Similar to the MP [ringbuffer](https://github.com/bslatkin/ringbuffer) but with threads instead of processes. 8 | 9 | As described [here](http://mechanitis.blogspot.com/2011/07/dissecting-disruptor-writing-to-ring.html), at its core, a Disruptor is: 10 | 11 | * A ring buffer into which producers can write elements to while consumers can consume elements from. 12 | * The ring has a finite size 13 | * The elements of the ring are pre-allocated 14 | * Every element placed into the ring has a sequence number 15 | * There can be many parallel producers: 16 | * When a producer needs to write an element into the ring 17 | * the disruptor picks the next available slot in the ring and writes the element there, incrementing the slot's sequence number 18 | * a slot is considered "Available" only after it has been consumed by all consumers in the disruptor 19 | * If there are no available slots, the producer is blocked until such time that there is a slot available 20 | * There can be many parallel consumers: 21 | * The disruptor creates a thread per consumer 22 | * Each consumer keeps track of the last sequence number it consumed 23 | * While there is data to be consumed, the consumer consumes data 24 | * When there is no data to be consumed (the consumer's sequence number is the highest sequence number in the ring), the consumer thread is blocked until there is data available 25 | 26 | This allows for an efficient setup for cases where an individual element needs to be consumed by several consumers at a maximum throughput. 27 | 28 | A more traditional approach of accomplishing concurrent consumption would be to have a set of parallel consumers simply consume batches of elements, with the producer waiting for each batch to be consumed by each consumer. This works OK when all consumers work at about the same speed, but is inefficient when some consumers/producers work slower than others. 29 | 30 | With a shared, finite ring buffer, these inefficiencies are largely eliminated. The throghput of data through the disruptor is still limited by the slowest consumer or producer. Unlike other approaches though, the structure guarantees that while there can be any work done (elements produced or consumed) it *is* being done - rather than various producer or consumer processes sitting idle. Effectively, a disruptor handles backpressure [really well](https://github.com/LMAX-Exchange/disruptor/wiki/Performance-Results) - especially in a "multicast" (e.g. `1P->3C`) configuration. 31 | 32 | Unlike [Java](https://github.com/LMAX-Exchange/disruptor), [.NET](https://github.com/disruptor-net/Disruptor-net), [C++](https://github.com/Abc-Arbitrage/Disruptor-cpp), and [C](https://github.com/systemtrader/c.LMAX-.disruptor) implementations of disruptors, this version does little in the way of "mechanical sympathy" through loading CPU cache lines. As a side-effect of the gil / python threads, mechanical sympathy is limited to being able to consume elements in batches. It's also generally unoptimized and produces a ton of garbage. On the other hand, this version does support: 33 | 34 | 1. producing/consuming big chunks of data at a time. 35 | 2. processing elements outside of any synchronization 36 | 37 | ## Usage 38 | 39 | ### Installing py-disruptor 40 | * via `requirements.txt`: 41 | ``` 42 | ... 43 | package==version 44 | ... 45 | -e git+https://github.com/pulsepointinc/py-disruptor.git@0.0.1#egg=py-disruptor==0.0.1 46 | ... 47 | ``` 48 | * via `pip` CLI: 49 | ``` 50 | pip install git+https://github.com/pulsepointinc/py-disruptor.git@0.0.1#egg=py-disruptor==0.0.1 51 | ``` 52 | ### Running a disruptor 53 | 54 | ```python 55 | from disruptor import Disruptor, Consumer 56 | import time, random 57 | 58 | class MyConsumer(Consumer): 59 | def __init__(self, name): 60 | self.name = name 61 | def consume(self, elements): 62 | # simulate some random processing delay 63 | time.sleep(random.random()) 64 | print("{} consumed {}".format(self.name,elements)) 65 | 66 | # Construct a couple of consumer instances 67 | consumer_one = MyConsumer(name = 'consumer one') 68 | consumer_two = MyConsumer(name = 'consumer two') 69 | 70 | # Construct a disruptor named example 71 | disruptor = Disruptor(name = 'Example', size = 3) 72 | try: 73 | # Register consumers 74 | disruptor.register_consumer(consumer_one) 75 | disruptor.register_consumer(consumer_two) 76 | 77 | for i in range(10): 78 | # Produce a bunch of elements 79 | element = 'element {}'.format(i) 80 | disruptor.produce([element]) 81 | print("produced {}".format(element)) 82 | finally: 83 | # Shut down the disruptor 84 | disruptor.close() 85 | ``` 86 | 87 | See [TestDisruptor](tests/test_disruptor.py#L137) for more examples 88 | 89 | ### Accessing disruptor statistics 90 | 91 | The `Disruptor` keeps track of producer and consumer statistics, including blocked time. They can be accessed via the `disruptor.stats` object 92 | 93 | ### Hints 94 | 95 | * Implement the `close` method inside consumers that require any kind of cleanup! 96 | * Make sure consumers don't hang forever. There are no timeout checks for consumption, so a hanging consumer means a hanging disruptor! 97 | 98 | ## Developing 99 | 100 | ### Testing 101 | To run unit tests, execute: 102 | * `python -m unittest tests` 103 | 104 | ### Releasing 105 | 106 | This is a simple project released entirely via github. To release, simply: 107 | 108 | 1. update `version` in [setup.py](setup.py) 109 | 2. run `git tag ` 110 | 3. update `README` usage as appropriate to point to the git tag 111 | 112 | -------------------------------------------------------------------------------- /disruptor/__init__.py: -------------------------------------------------------------------------------- 1 | from .disruptor import Disruptor, Consumer, BatchConsumer 2 | -------------------------------------------------------------------------------- /disruptor/disruptor.py: -------------------------------------------------------------------------------- 1 | from threading import RLock, Thread, Condition, Event 2 | import time 3 | 4 | 5 | class RingBuffer(object): 6 | """ 7 | Fast, list backed, preallocated Ring Buffer with static size. Not thread safe and has no safety checking. 8 | """ 9 | 10 | def __init__(self, size): 11 | """ 12 | Construct a RingBuffer 13 | :param size: size of buffer 14 | :type size: int 15 | """ 16 | self.buffer = [] 17 | self.size = size 18 | for i in range(self.size): 19 | self.buffer.append(None) 20 | 21 | def set(self, index, element): 22 | """ 23 | Set a single element at supplied positive index; index can wrap around size of buffer 24 | 25 | :param index: a positive index - can wrap around size of buffer 26 | :type index: int 27 | :param element: element to set 28 | :type element: * 29 | :returns: self 30 | :rtype: RingBuffer 31 | """ 32 | self.buffer[index % self.size] = element 33 | return self 34 | 35 | def get(self, index): 36 | """ 37 | Get a single element at supplied positive index; index can wrap around size of buffer 38 | 39 | :param index: a positive index - can wrap around size of buffer 40 | :returns: element at index 41 | :rtype: * 42 | """ 43 | return self.buffer[index % self.size] 44 | 45 | def mget(self, start_index, count): 46 | """ 47 | Get multiple elements from buffer 48 | 49 | :param start_index: a positive start index - can wrap around size of buffer 50 | :type start_index: int 51 | :param count: number of elements to get - must be >= 0 52 | :type count: int 53 | :returns: list of elements 54 | :rtype: list 55 | """ 56 | s_index = start_index % self.size 57 | if s_index + count > self.size: 58 | return self.buffer[s_index:] + self.buffer[0:(s_index + count) - self.size] 59 | else: 60 | return self.buffer[s_index:s_index+count] 61 | 62 | def mset(self, start_index, elements): 63 | """ 64 | Set multiple elements in buffer 65 | 66 | :param start_index: a positive start index - can wrap around size of buffer 67 | :type start_index: int 68 | :param elements: collection of elements 69 | :type elements: list 70 | :returns: self 71 | :rtype: RingBuffer 72 | """ 73 | s_index = start_index % self.size 74 | if s_index + len(elements) > self.size: 75 | self.buffer[s_index:self.size] = elements[0:self.size - s_index] 76 | self.buffer[0:len(elements) - (self.size - s_index) 77 | ] = elements[self.size-s_index:len(elements)] 78 | else: 79 | self.buffer[s_index:s_index + 80 | len(elements)] = elements[0:len(elements)] 81 | 82 | 83 | class ConsumerStats(object): 84 | """ 85 | Statistics object for keeping track of consumer stats 86 | """ 87 | 88 | def __init__(self, consumer_t): 89 | """ 90 | Construct a consuemr for a consumer thread 91 | :param consumer_t: consumer thread 92 | :type consumer_t: ConsumerThread 93 | """ 94 | self.consumer_t = consumer_t 95 | self.blocked_sec = 0 96 | self.consumed = 0 97 | self.consumption_sec = 0 98 | 99 | def report_blocked(self, sec): 100 | """ 101 | Report an instance of a consumer being blocked on production for supplied seconds 102 | :param sec: time consumer was blocked in seconds 103 | :type sec: float 104 | """ 105 | self.blocked_sec = self.blocked_sec + sec 106 | 107 | def report_consumed(self, n_elements, sec): 108 | """ 109 | Report a consumer consuming a number of elements over some time period in seconds 110 | :param n_elements: number of elements consumed 111 | :type n_elements: int 112 | :param sec: time taken to consume elements 113 | :type sec: float 114 | """ 115 | self.consumed = self.consumed + n_elements 116 | self.consumption_sec = self.consumption_sec + sec 117 | 118 | @property 119 | def cps(self): 120 | """ 121 | Return elements consumed per second 122 | :returns: elements consumed per second 123 | :rtype: float 124 | """ 125 | if self.consumption_sec > 0: 126 | return self.consumed / self.consumption_sec 127 | else: 128 | return 0 129 | 130 | def __str__(self): 131 | return '\n'.join([ 132 | 'Consumer: {}'.format(self.consumer_t.consumer), 133 | ' blocked_sec:{}'.format(self.blocked_sec), 134 | ' consumed:{}'.format(self.consumed), 135 | ' consume_sec:{}'.format(self.consumption_sec), 136 | ' cps:{}'.format(self.cps) 137 | ]) 138 | 139 | 140 | class RingBufferLagStats(object): 141 | """ 142 | Basic disruptor ring buffer "lag" statistics 143 | used to keep track of how far the slowest consumer is behind producers 144 | """ 145 | 146 | def __init__(self): 147 | self.cur_lag = 0 148 | self.max_lag = 0 149 | self.avg_lag = 0 150 | self.n_samples = 0 151 | 152 | def sample(self, lag): 153 | """ 154 | Supply a lag sample 155 | :param lag: number of elements slowest consumer is behind producers 156 | :type lag: int 157 | """ 158 | self.cur_lag = lag 159 | if lag > self.max_lag: 160 | self.max_lag = lag 161 | self.avg_lag = ((self.avg_lag * self.n_samples) + lag) / \ 162 | (self.n_samples + 1) 163 | self.n_samples = self.n_samples + 1 164 | 165 | def __str__(self): 166 | return 'cur_lag: {}, avg_lag: {}, max_lag: {}'.format(self.cur_lag, self.avg_lag, self.max_lag) 167 | 168 | 169 | class DisruptorStats(object): 170 | """ 171 | Disruptor statistics container 172 | """ 173 | 174 | def __init__(self, time_fn): 175 | self.time_fn = time_fn 176 | self.consumer_stats = {} 177 | self.p_blocked_sec = 0 178 | self.produced = 0 179 | self.ring_lag_stats = RingBufferLagStats() 180 | self.start_time = time_fn() 181 | self.end_time = None 182 | 183 | def report_c_consumed(self, consumer_t, n_elements, sec): 184 | """ 185 | Report a consumer thread consuming some number of elements 186 | :param consumer_t: a ConsumerThread 187 | :type consumer_t: ConsumerThread 188 | :param n_elements: number of elements consumed 189 | :type n_elements: int 190 | :param sec: time taken to consume elements 191 | :type sec: float 192 | """ 193 | self.consumer_stats.setdefault(consumer_t.thread.name, ConsumerStats( 194 | consumer_t)).report_consumed(n_elements, sec) 195 | 196 | def report_p_produced(self, n_elements): 197 | """ 198 | Report a producer producing some elements into the disruptor 199 | :param n_elements: number of elements produced 200 | """ 201 | self.produced = self.produced + n_elements 202 | 203 | def report_c_blocked(self, consumer_t, sec): 204 | """ 205 | Report an instance of a consumer being blocked on production for supplied seconds 206 | :param consumer_t: a ConsumerThread 207 | :type consumer_t: ConsumerThread 208 | :param sec: time consumer was blocked in seconds 209 | :type sec: float 210 | """ 211 | self.consumer_stats.setdefault(consumer_t.thread.name, ConsumerStats( 212 | consumer_t)).report_blocked(sec) 213 | 214 | def report_p_blocked(self, sec): 215 | """ 216 | Report a publisher being blocked on a "full" ring for supplied number of seconds 217 | :param sec: time producer was blocked in seconds 218 | :type sec: float 219 | """ 220 | self.p_blocked_sec = self.p_blocked_sec + sec 221 | 222 | def report_ring_lag(self, lag_size): 223 | """ 224 | Report some ring lag 225 | :param lag_size: number of elements slowest consumer is behind producers 226 | :type lag_size: int 227 | """ 228 | self.ring_lag_stats.sample(lag_size) 229 | 230 | def close(self): 231 | self.end_time = self.time_fn() 232 | 233 | @property 234 | def production_sec(self): 235 | """ 236 | Return number of seconds disruptor was operational 237 | :returns: number of seconds disruptor was operational 238 | :rtype: float 239 | """ 240 | if self.end_time != None: 241 | return self.end_time - self.start_time 242 | else: 243 | return self.time_fn() - self.start_time 244 | 245 | @property 246 | def pps(self): 247 | """ 248 | Return elements produced per second 249 | :returns: elements produced per second 250 | :rtype: float 251 | """ 252 | if self.production_sec > 0: 253 | return self.produced / self.production_sec 254 | else: 255 | return 0 256 | 257 | def __str__(self): 258 | return '\n'.join([ 259 | 'Ring: {}'.format(self.ring_lag_stats), 260 | 'Producers:', 261 | ' blocked_sec:{}'.format(self.p_blocked_sec), 262 | ' produced:{}'.format(self.produced), 263 | ' produce_sec:{}'.format(self.production_sec), 264 | ' pps:{}'.format(self.pps), 265 | ] + [str(value) for (key, value) in self.consumer_stats.items()]) 266 | 267 | 268 | class RingSynchronizer(object): 269 | """ 270 | Disruptor synchronization uitlity 271 | """ 272 | 273 | def __init__(self): 274 | """ 275 | Construct RingSynchronizer 276 | """ 277 | self.lock = RLock() 278 | self.produced_condition = Condition(self.lock) 279 | self.consumed_condition = Condition(self.lock) 280 | 281 | def __enter__(self): 282 | self.lock.acquire() 283 | 284 | def __exit__(self, t, v, tb): 285 | self.lock.release() 286 | 287 | def await_production(self, timeout_sec=5): 288 | """ 289 | Block calling thread for supplied amount of time or until a production condition occurs 290 | 291 | :param timeout_sec: timeout seconds 292 | :type timeout_sec: float 293 | """ 294 | with self.lock: 295 | self.produced_condition.wait(timeout_sec) 296 | 297 | def await_consumption(self, timeout_sec=5): 298 | """ 299 | Block calling thread for supplied amount of time or until a consumption condition occurs 300 | 301 | :param timeout_sec: timeout seconds 302 | :type timeout_sec: float 303 | """ 304 | with self.lock: 305 | self.consumed_condition.wait(timeout_sec) 306 | 307 | def notify_production(self): 308 | """ 309 | Notify and unblock all threads waiting on a production condition 310 | """ 311 | with self.lock: 312 | self.produced_condition.notify_all() 313 | 314 | def notify_consumption(self): 315 | """ 316 | Notify and unblock all threads waiting on a consumption condition 317 | """ 318 | with self.lock: 319 | self.consumed_condition.notify_all() 320 | 321 | 322 | class ConsumerThread(object): 323 | """ 324 | A disruptor consumption thread wrapper 325 | """ 326 | 327 | def __init__(self, disruptor, consumer): 328 | self.disruptor = disruptor 329 | self.consumer = consumer 330 | self.seqnum = disruptor.producer_seqnum 331 | self.thread = Thread( 332 | name='{}_Consumer_{}'.format(disruptor.name, consumer), target=self.run) 333 | self.thread.start() 334 | 335 | def run(self): 336 | """ 337 | Consume while there's something to consume! 338 | """ 339 | available_count = 0 340 | to_consume = None 341 | while self.disruptor.running: 342 | 343 | # report ring lag once in a while 344 | self.disruptor._unsafe_report_lag() 345 | 346 | while available_count == 0 and self.disruptor.running: 347 | # atomically check+fetch available data and go to sleep if none 348 | with self.disruptor.sync: 349 | available_count = self.disruptor.producer_seqnum - self.seqnum 350 | if available_count > 0: 351 | to_consume = self.disruptor.ring_buffer.mget( 352 | self.seqnum, available_count) 353 | else: 354 | s = self.disruptor.time_fn() 355 | self.disruptor.sync.await_production() 356 | self.disruptor.stats.report_c_blocked( 357 | self, self.disruptor.time_fn()-s) 358 | 359 | # when data is available, consume it *outside* of lock! 360 | self._consume_safe(to_consume) 361 | 362 | # re-lock after consumption to update state 363 | with self.disruptor.sync: 364 | self.seqnum = self.seqnum + available_count 365 | self.disruptor.sync.notify_consumption() 366 | available_count = 0 367 | to_consume = None 368 | 369 | # after disruptor stops, consume the rest of available data 370 | to_consume = None 371 | with self.disruptor.sync: 372 | available_count = self.disruptor.producer_seqnum - self.seqnum 373 | if available_count > 0: 374 | to_consume = self.disruptor.ring_buffer.mget( 375 | self.seqnum, available_count) 376 | self._consume_safe(to_consume) 377 | self.consumer.close() 378 | 379 | def _consume_safe(self, elements): 380 | if elements != None and len(elements) > 0: 381 | s = self.disruptor.time_fn() 382 | try: 383 | self.consumer.consume(elements) 384 | except Exception as e: 385 | if self.disruptor.consumer_error_handler != None: 386 | self.disruptor.consumer_error_handler( 387 | self.consumer, elements, e) 388 | self.disruptor.stats.report_c_consumed( 389 | self, len(elements), self.disruptor.time_fn() - s) 390 | 391 | 392 | class Disruptor(object): 393 | """ 394 | A basic multi-threaded RingBuffer; a Disruptor-Lite implementation using a thread-per-consumer model. 395 | 396 | This is an efficient alternative to queues in cases where multiple workloads need to consume the same type of data. 397 | 398 | See the below links for an explanation of how this works: 399 | * http://mechanitis.blogspot.com/2011/07/dissecting-disruptor-writing-to-ring.html explanation of structure 400 | * https://lmax-exchange.github.io/disruptor/ original Disruptor 401 | * https://medium.com/@teivah/understanding-the-lmax-disruptor-caaaa2721496 - mechanical sympathy (largely not applicable in python) 402 | 403 | Allows for many producers to efficiently concurrently produce elements to be concurrently consumed by many consumers. 404 | Uses a shared ring buffer between consumers and producers with a minimum amount of blocking. An element in the ring 405 | can only be written to after all consumers have consumed it, effectively handling backpressure from any number of 406 | parallel consumers. 407 | 408 | Producers (callers of the produce method) are only blocked when the ring is full. 409 | 410 | Unlike a C/C++/C#/Java disruptor, this implementation uses Python threads, so it offers little to no mechanical sympathy 411 | outside of supporting lock-free parallel consumptions of big sections of the ring buffer which may or may not fall into 412 | a single CPU cache line. Even so, this is a great tool for processing multiple events of the same type concurrently. 413 | """ 414 | 415 | def __init__(self, size=1024, name='Disruptor', consumer_error_handler=None, time_fn=time.time): 416 | """ 417 | Initialize a disruptor of supplied size 418 | :param size: size of disruptor ring buffer 419 | :type size: int 420 | :param name: disruptor name (used in naming consumer threads) 421 | :type name: str 422 | :param consumer_error_handler: optional function invoked if a consumer fails to consume data. Must accept a consumer instance, input to consumer, and error 423 | :type consumer_error_handler: Function 424 | :param time_fn: zero argument time provider function - defaults to time.time(); used strictly for statistics 425 | :type time_fn: Function 426 | """ 427 | self.name = name 428 | self.time_fn = time_fn 429 | self.consumer_error_handler = consumer_error_handler 430 | self.stats = DisruptorStats(time_fn) 431 | self.ring_buffer = RingBuffer(size) 432 | self.sync = RingSynchronizer() 433 | self.producer_seqnum = 0 434 | self.consumers = [] 435 | self.running = True 436 | 437 | def produce(self, elements): 438 | """ 439 | Produce multiple elements, blocking if the disruptor is full 440 | 441 | :param elements: list of elements to produce 442 | :type elements: list 443 | """ 444 | if not self.running: 445 | raise Exception('Disruptor is stopped') 446 | 447 | # report ring lag once in a while 448 | self._unsafe_report_lag() 449 | 450 | produced = 0 451 | 452 | while produced < len(elements): 453 | with self.sync.lock: 454 | # figure out maximum number of elements producer can produce 455 | # the producer can produce up to the slowest consumer slot 456 | # 457 | # Example: 458 | # 459 | # - Ring size = 30 460 | # 461 | # seq# ring idx 462 | # - Consumer 1 (C1) = 83 13 463 | # - Consumer 2 (C2) = 78 8 464 | # - Producer seq = 88 18 465 | # 466 | # C2 C1 P 467 | # | | | 468 | # ringidx 00 05 | 10 | 15 | 20 30 469 | # |----|--|-|--|-|--|-|----| 470 | # seqnum 70 75 | 80 | 85 | 90 100 471 | # | | |======> 472 | # =======>| | | 473 | # 474 | # The producer can produce up to the slowest consumer's (C2) slot 475 | # in the ring (8) - outlined by "==>" 476 | # 477 | # There's several ways of computing this: 478 | # 479 | # * (ring_size - p_idx) + min(C1_idx, C2_idx) 480 | # (30 - 18 ) + 8 = 20 481 | # * ring_size - p_seq + min(C1_seq, C2_seq) 482 | # 30 - 88 + 78 = 20 483 | # 484 | # This code uses the second approach because it doesn't require 485 | # computing an index in the ring buffer. 486 | can_produce = self.ring_buffer.size - self.producer_seqnum + \ 487 | min(map(lambda c: c.seqnum, self.consumers)) 488 | if can_produce <= 0: 489 | s = self.time_fn() 490 | self.sync.await_consumption() 491 | self.stats.report_p_blocked(self.time_fn()-s) 492 | else: 493 | to_produce_cnt = min(can_produce, len(elements) - produced) 494 | self.ring_buffer.mset( 495 | self.producer_seqnum, elements[produced:produced+to_produce_cnt:]) 496 | produced += to_produce_cnt 497 | self.producer_seqnum += to_produce_cnt 498 | self.sync.notify_production() 499 | 500 | self.stats.report_p_produced(produced) 501 | 502 | def close(self): 503 | """ 504 | Close the disruptor, block (potentially indefinitely) until consumers finish consuming all elements 505 | """ 506 | with self.sync.lock: 507 | if self.running: 508 | self.running = False 509 | # wake up any threads waiting on production 510 | self.sync.notify_production() 511 | for consumer in self.consumers: 512 | consumer.thread.join() 513 | self.stats.close() 514 | 515 | def register_consumer(self, consumer): 516 | """ 517 | Register a consumer for this disruptor. Once registered, a consumer can not be de-registered! 518 | 519 | :param consumer: a Consumer 520 | :type consumer: Consumer 521 | """ 522 | self.consumers.append(ConsumerThread(self, consumer)) 523 | return self 524 | 525 | def _unsafe_report_lag(self): 526 | if self.producer_seqnum % 10 == 3: 527 | self.stats.report_ring_lag( 528 | self.producer_seqnum - min(map(lambda c: c.seqnum, self.consumers))) 529 | 530 | def __str__(self): 531 | return 'Disruptor-"{}"'.format(self.name) 532 | 533 | def __del__(self): 534 | self.close() 535 | 536 | 537 | class Consumer(object): 538 | """ 539 | A no-op consumer class; can be extended for convenience 540 | """ 541 | 542 | def consume(self, elements): 543 | """ 544 | Consume elements 545 | :param elements: a list of elements 546 | :type elements: list 547 | """ 548 | raise NotImplementedError() 549 | 550 | def close(self): 551 | """ 552 | Close consumer, finishing any consumption tasks e.g. terminating batches 553 | """ 554 | pass 555 | 556 | def __str__(self): 557 | return self.__class__.__name__ 558 | 559 | 560 | class BatchConsumer(Consumer): 561 | """ 562 | A Consumer that buffers incoming elements into batches of specified size without using iteration. 563 | 564 | Useful for workloads that are optimized to a specific batch size. 565 | """ 566 | 567 | def __init__(self, batch_size): 568 | """ 569 | Construct a BatchConsumer with supplied batch size 570 | :param batch_size: a batch size 571 | :type batch_size: int 572 | """ 573 | self.batch_size = batch_size 574 | self._batch = [] 575 | 576 | def consume(self, elements): 577 | consumed = 0 578 | while consumed < len(elements): 579 | to_consume_cnt = min( 580 | self.batch_size - len(self._batch), len(elements)-consumed) 581 | self._batch.extend(elements[consumed:consumed+to_consume_cnt]) 582 | if len(self._batch) >= self.batch_size: 583 | self.consume_batch(self._batch) 584 | self._batch = [] 585 | consumed += to_consume_cnt 586 | 587 | def close(self): 588 | if len(self._batch) > 0: 589 | self.consume_batch(self._batch) 590 | 591 | def consume_batch(self, batch): 592 | """ 593 | Consume a batch of elements 594 | :param batch: a batch of elements of batch_size or smaller 595 | :type batch: list 596 | """ 597 | raise NotImplementedError() 598 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from setuptools import setup, find_packages 3 | 4 | setup(name='py-disruptor', 5 | version='0.0.1', 6 | description='Python Disruptor-Lite implementation', 7 | author='erachitskiy', 8 | author_email='erachitskiy@pulsepoint.com', 9 | url='https://github.com/pulsepointinc/py-disruptor', 10 | packages=['disruptor', ], 11 | ) 12 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | from .test_disruptor import * -------------------------------------------------------------------------------- /tests/test_disruptor.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from disruptor import Disruptor, BatchConsumer, Consumer 4 | from disruptor.disruptor import RingBuffer, RingBufferLagStats 5 | from threading import Event 6 | import time 7 | import random 8 | import logging 9 | 10 | 11 | class TestRingBuffer(TestCase): 12 | @classmethod 13 | def setUpClass(cls): 14 | cls.logger = logging.getLogger(cls.__name__) 15 | cls.logger.level = logging.DEBUG 16 | 17 | def test_get_set(self): 18 | ring = RingBuffer(5) 19 | # assert intial ring state with wrap-around 20 | for idx in range(10): 21 | self.assertEqual(None, ring.get(idx)) 22 | # set some elements 23 | for idx in range(10): 24 | ring.set(idx, idx) 25 | # assert values 26 | for idx in range(5): 27 | self.assertEqual(idx + 5, ring.get(idx)) 28 | 29 | def test_mget_mset(self): 30 | ring = RingBuffer(10) 31 | for idx in range(10): 32 | ring.set(idx, idx) 33 | 34 | ring.mset(0, [9, 9, 9]) 35 | # ring is now [9,9,9,3,4,5,6,7,8,9] 36 | self.assertEqual([9, 9, 9, 3], ring.mget(0, 4)) 37 | self.assertEqual([9, 9, 3, 4], ring.mget(1, 4)) 38 | self.assertEqual([8, 9, 9, 9, 9, 3], ring.mget(8, 6)) 39 | ring.mset(8, [1, 2, 3, 4]) 40 | # ring is now [3,4,9,3,4,5,6,7,1,2] 41 | self.assertEqual([3, 4, 9, 3, 4, 5, 6, 7, 1, 2], ring.mget(0, 10)) 42 | self.assertEqual([4, 9, 3, 4, 5, 6, 7, 1, 2, 3], ring.mget(1, 10)) 43 | ring.mset(11, [0, 1, 2]) 44 | # ring is now [3,0,1,2,4,5,6,7,1,2] 45 | self.assertEqual([0, 1, 2, 4], ring.mget(11, 4)) 46 | 47 | # This test is skipped as it is a benchmarking only test 48 | def test_mperf(self): 49 | """ 50 | Sanity test to make sure that mget/mset impelementations of array slicing are faster than 51 | basic index by index fetch/updates 52 | """ 53 | def inc_mget(ring, idx, count): 54 | ret = [] 55 | end_idx = idx + count 56 | while idx < end_idx: 57 | ret.append(ring.get(idx)) 58 | idx = idx + 1 59 | return ret 60 | 61 | def inc_mset(ring, idx, elements): 62 | c = 0 63 | for e in elements: 64 | ring.set(idx + c, e) 65 | c = c + 1 66 | # time performance 67 | iterations = 200000 68 | set_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 69 | ring = RingBuffer(10) 70 | 71 | start = time.time() 72 | for t in range(iterations): 73 | ring.mset(t, set_list) 74 | self.assertEqual(set_list, ring.mget(t, 10)) 75 | m_runtime = time.time() - start 76 | 77 | start = time.time() 78 | for t in range(iterations): 79 | inc_mset(ring, t, set_list) 80 | self.assertEqual(set_list, inc_mget(ring, t, 10)) 81 | inc_runtime = time.time() - start 82 | 83 | self.logger.debug( 84 | 'For {} iterations, mget/mset: {}s, inc_mget/inc_mset: {}s'.format(iterations, m_runtime, inc_runtime)) 85 | 86 | self.assertTrue(m_runtime < inc_runtime) 87 | 88 | 89 | class TestRingBufferLagStats(TestCase): 90 | def test_avg(self): 91 | s = RingBufferLagStats() 92 | s.sample(1) 93 | self.assertEqual(1, s.avg_lag) 94 | s.sample(3) 95 | self.assertEqual(2, s.avg_lag) 96 | s.sample(2) 97 | self.assertEqual(2, s.avg_lag) 98 | 99 | 100 | class MemoryConsumer(BatchConsumer): 101 | def __init__(self, name, batch_size): 102 | super(MemoryConsumer, self).__init__(batch_size) 103 | self.consumed = [] 104 | self.name = name 105 | 106 | def consume_batch(self, elements): 107 | self.consumed = self.consumed + elements 108 | 109 | def __str__(self): 110 | return str(self.name) 111 | 112 | 113 | class BrokenConsumer(Consumer): 114 | exception = Exception('I am broken') 115 | 116 | def consume(self, elements): 117 | raise self.exception 118 | 119 | 120 | class TestBatchConsumer(TestCase): 121 | def test_batching(self): 122 | c = MemoryConsumer('test', batch_size=3) 123 | # consume less than batch size and verify nothing happens 124 | c.consume([1]) 125 | self.assertEqual([], c.consumed) 126 | # consume up to batch size and verify consumption occurs 127 | c.consume([2, 3]) 128 | self.assertEqual([1, 2, 3], c.consumed) 129 | # consume over batch size and verify consumption occurs 130 | c.consume([4, 5, 6, 7, 8]) 131 | self.assertEqual([1, 2, 3, 4, 5, 6], c.consumed) 132 | # close consumer and verify remainder of elements is consumed 133 | c.close() 134 | self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8], c.consumed) 135 | 136 | 137 | class TestDisruptor(TestCase): 138 | def __init__(self, *args, **kwargs): 139 | super(TestDisruptor, self).__init__(*args, **kwargs) 140 | 141 | @classmethod 142 | def setUpClass(cls): 143 | cls.logger = logging.getLogger(cls.__name__) 144 | cls.logger.level = logging.DEBUG 145 | cls.maxDiff = None 146 | 147 | def random_batch_iterator(self, iterable, min_batch_size, max_batch_size): 148 | batch_size = random.randint(min_batch_size, max_batch_size) 149 | batch = [] 150 | for e in iterable: 151 | batch.append(e) 152 | if len(batch) >= batch_size: 153 | yield batch 154 | batch_size = random.randint(min_batch_size, max_batch_size) 155 | batch = [] 156 | if len(batch) > 0: 157 | yield batch 158 | 159 | def test_error_handling(self): 160 | handled_errors = [] 161 | 162 | def error_handler(consumer, elements, error): 163 | handled_errors.append({ 164 | 'consumer': consumer, 165 | 'elements': elements, 166 | 'error': error 167 | }) 168 | disruptor = Disruptor(1, consumer_error_handler=error_handler) 169 | broken_consumer = BrokenConsumer() 170 | working_consumer = MemoryConsumer('Working Consumer', 3) 171 | try: 172 | disruptor.register_consumer(broken_consumer) 173 | disruptor.register_consumer(working_consumer) 174 | disruptor.produce(['Test element']) 175 | finally: 176 | disruptor.close() 177 | # verify working consumer processed elements 178 | self.assertEqual(['Test element'], working_consumer.consumed) 179 | # verify error handler was called when broken consumer failed to consume a batch of elements 180 | self.assertEqual([{ 181 | 'consumer': broken_consumer, 182 | 'elements': ['Test element'], 183 | 'error': broken_consumer.exception 184 | }], handled_errors) 185 | 186 | def test_disruptor(self): 187 | elements_to_produce = 10000 188 | min_batch_size = 1 189 | max_batch_size = 12 190 | ring_size = 8 191 | n_consumers = 3 192 | 193 | # make some consumers with variable batch sizes 194 | consumers = [MemoryConsumer(i, i+2) for i in range(n_consumers)] 195 | # make a disruptor 196 | disruptor = Disruptor(ring_size) 197 | try: 198 | # register consumers 199 | for consumer in consumers: 200 | disruptor.register_consumer(consumer) 201 | # make an array of elements to produce 202 | to_produce = [x for x in range(elements_to_produce)] 203 | # make a random size batched iterator of elements 204 | rnd_batch = self.random_batch_iterator( 205 | to_produce, min_batch_size=min_batch_size, max_batch_size=max_batch_size) 206 | # produce! 207 | for batch in rnd_batch: 208 | disruptor.produce(batch) 209 | finally: 210 | # shut down disruptor 211 | disruptor.close() 212 | 213 | # assert stats 214 | self.assertEqual(elements_to_produce, disruptor.stats.produced) 215 | self.logger.info(str(disruptor.stats)) 216 | 217 | expected_results = to_produce 218 | # assert consumption 219 | for consumer in consumers: 220 | self.assertEqual(expected_results, consumer.consumed) 221 | 222 | def test_batch_alignment(self): 223 | # this verifies that batches that align perfectly do not hang disruptor.close 224 | consumer = MemoryConsumer('test', batch_size=1) 225 | # patch consumer with a latch that gets hit after it consumes any elements 226 | consumed_latch = Event() 227 | consume_original = consumer.consume 228 | 229 | def patched_consume(elements): 230 | try: 231 | return consume_original(elements) 232 | finally: 233 | consumed_latch.set() 234 | consumer.consume = patched_consume 235 | 236 | disruptor = Disruptor(1) 237 | try: 238 | disruptor.register_consumer(consumer) 239 | # produce an element 240 | disruptor.produce(['element']) 241 | # wait until element is processed by consumer 242 | consumed_latch.wait(10) 243 | finally: 244 | # close the disruptor to verify there is no hangup 245 | disruptor.close() 246 | 247 | self.assertEqual(['element'], consumer.consumed) 248 | --------------------------------------------------------------------------------