├── .gitattributes ├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── circuit ├── __init__.py ├── _twisted.py ├── breaker.py └── test │ ├── __init__.py │ ├── test_breaker.py │ └── test_twisted.py └── setup.py /.gitattributes: -------------------------------------------------------------------------------- 1 | circuit/_version.py export-subst 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.pyc 3 | \.gitignore 4 | dist 5 | env 6 | MANIFEST 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "2.6" 5 | - "2.7" 6 | - "3.4" 7 | 8 | install: 9 | - pip install pep8 frosted 10 | 11 | script: 12 | - make check 13 | - make test 14 | 15 | sudo: false 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include circuit *.py 2 | include versioneer.py 3 | include README.md 4 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | 3 | prepare: 4 | 5 | check: frosted pep8 6 | 7 | pep8: 8 | pep8 circuit 9 | 10 | frosted: 11 | frosted -vb -r circuit 12 | 13 | test: 14 | python setup.py test 15 | 16 | build: 17 | 18 | dist: 19 | 20 | clean: 21 | git clean -fdx 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/edgeware/python-circuit.svg?branch=master)](https://travis-ci.org/edgeware/python-circuit) 2 | 3 | A circuit breaker according to the logic outline in Michael T. Nygard's 4 | great book [Release It!](http://www.amazon.com/Release-It-Production-Ready-Pragmatic-Programmers/dp/0978739213). 5 | 6 | Read: http://en.wikipedia.org/wiki/Circuit_breaker_design_pattern 7 | 8 | The circuit breaker monitors communication with a remote peer and in 9 | the case of a high error rate may break the circuit and not allow 10 | further communication for a short period. After a while the breaker 11 | will let through a single request to probe to see if the peer feels 12 | better. If it does, it will close the circuit and allow requests once 13 | again. If not, it will open the circuit again. 14 | 15 | A `CircuitBreakerSet` can handle the state for multiple peers at the 16 | same time. Use the `context` method to pick which peer to track. The 17 | first argument is used to identify the peer. Make it a string of some 18 | kind, since it will be used to identify the peer in logs. 19 | 20 | Below is a small example of how the circuit breaker can be used: 21 | 22 | ```python 23 | import logging 24 | import time 25 | 26 | from circuit import CircuitBreakerSet 27 | 28 | circuit_breaker = CircuitBreakerSet(time.time, logging.getLogger( 29 | 'circuit-breaker')) 30 | circuit_breaker.handle_error(ValueError) 31 | 32 | def fn(circuit_breaker): 33 | try: 34 | with circuit_breaker.context('my-remote-peer'): 35 | raise ValueError('oh no') 36 | except CircuitOpenError: 37 | # the circuit was open so we did not even try to communicate 38 | # with the remote service. 39 | raise 40 | ``` 41 | 42 | If you call `fn` often enough the circuit breaker will open and 43 | `CircuitOpenError` will be raised. 44 | 45 | The `CircuitBreakerSet` class takes a few keyword arguments: 46 | 47 | * `time_unit` (default 60) -- Number of seconds to sample seconds over. 48 | * `maxfail` (default 3) -- Number of seconds that is allowed over a time unit. 49 | * `reset_timeout` (default 10) -- Seconds that the circuit is open before 50 | going into half-open mode. 51 | 52 | It is also possible to create a single instance of a circuit breaker. The 53 | `circuit.CircuitBreaker` class takes the following arguments: 54 | 55 | * `clock` -- A callable that returns the time in seconds. 56 | * `log` -- a `logging.Logger` object used for logging. 57 | * `error_types` -- A list of error types that are treated as errors. 58 | * `maxfail` -- Number of seconds that is allowed over a time unit. 59 | * `reset_timeout` -- Seconds that the circuit is open before 60 | going into half-open mode. 61 | * `time_unit` -- Number of seconds to sample seconds over. 62 | 63 | 64 | # Twisted Support # 65 | 66 | There's also support for using the circuit breaker with Twisted. Note that 67 | the circuit breaker still use python's standard logging framework. Example: 68 | 69 | ```python 70 | import logger 71 | 72 | from circuit import TwistedCircuitBreakerSet 73 | 74 | circuit_breaker = TwistedCircuitBreakerSet(reactor, logging.getLogger( 75 | 'circuit-breaker')) 76 | ``` 77 | 78 | (The `TwistedCircuitBreakerSet` adds support for `defer.returnValue` 79 | which uses exceptions internally.) 80 | 81 | # License # 82 | 83 | Copyright 2012 Edgeware AB. 84 | 85 | Licensed under the Apache License, Version 2.0 (the "License"); 86 | you may not use this file except in compliance with the License. 87 | You may obtain a copy of the License at 88 | 89 | http://www.apache.org/licenses/LICENSE-2.0 90 | 91 | Unless required by applicable law or agreed to in writing, software 92 | distributed under the License is distributed on an "AS IS" BASIS, 93 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 94 | See the License for the specific language governing permissions and 95 | limitations under the License. 96 | 97 | 98 | # Thanks # 99 | 100 | * Michael Nygard, http://www.michaelnygard.com/, for writing the Release It! 101 | book that outlines the circuit breaker pattern 102 | 103 | * Edgeware, http://www.edgeware.tv/, for sponsoring the development of 104 | python-circuit. 105 | -------------------------------------------------------------------------------- /circuit/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012 Edgeware AB. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from .breaker import CircuitBreakerSet, CircuitBreaker, CircuitOpenError # noqa 16 | from ._twisted import TwistedCircuitBreakerSet # noqa 17 | -------------------------------------------------------------------------------- /circuit/_twisted.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012 Edgeware AB. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from circuit.breaker import CircuitBreaker, CircuitBreakerSet 16 | try: 17 | from twisted.internet import defer 18 | except ImportError: 19 | pass 20 | 21 | 22 | class TwistedCircuitBreaker(CircuitBreaker): 23 | """Circuit breaker that know that L{defer.inlineCallbacks} use 24 | exceptions in its internal workings. 25 | """ 26 | 27 | def __exit__(self, exc_type, exc_val, tb): 28 | if exc_type is defer._DefGen_Return: 29 | exc_type, exc_val, tb = None, None, None 30 | return CircuitBreaker.__exit__(self, exc_type, exc_val, tb) 31 | 32 | 33 | class TwistedCircuitBreakerSet(CircuitBreakerSet): 34 | """Circuit breaker that supports twisted.""" 35 | 36 | def __init__(self, reactor, logger, **kwargs): 37 | kwargs.update({'factory': TwistedCircuitBreaker}) 38 | CircuitBreakerSet.__init__(self, reactor.seconds, logger, **kwargs) 39 | -------------------------------------------------------------------------------- /circuit/breaker.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012 Edgeware AB. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Functionality for managing errors when interacting with a remote 16 | service. 17 | 18 | The circuit breaker monitors the communication and in the case of a 19 | high error rate may break the circuit and not allow further 20 | communication for a short period. After a while the breaker will let 21 | through a single request to probe to see if the service feels better. 22 | If not, it will open the circuit again. 23 | 24 | Note the optional parameters for back-off_cap and with_jitter. If back-off on 25 | retries is desired, set the back-off_cap to the maximum back-off value. 26 | Empirical data (http://www.awsarchitectureblog.com/2015/03/backoff.html) 27 | indicates adding jitter (randomness) to back-off strategies can lead to an 28 | increased throughput for a system experiencing contention for a shared 29 | resource. If using a L{CircuitBreaker} with a contended resource it may be 30 | beneficial to use back-off with jitter. 31 | 32 | A L{CircuitBreakerSet} can handle the state for multiple interactions 33 | at the same time. Use the C{context} method to pick which interaction 34 | to track: 35 | 36 | try: 37 | with circuit_breaker.context('x'): 38 | # something that generates errors 39 | pass 40 | except CircuitOpenError: 41 | # the circuit was open so we did not even try to communicate 42 | # with the remote service. 43 | pass 44 | 45 | """ 46 | import random 47 | 48 | 49 | class CircuitOpenError(Exception): 50 | """The circuit breaker is open.""" 51 | 52 | 53 | class CircuitBreaker(object): 54 | """A single circuit with breaker logic.""" 55 | 56 | def __init__(self, clock, log, error_types, maxfail, reset_timeout, 57 | time_unit, backoff_cap=None, with_jitter=False): 58 | self.clock = clock 59 | self.log = log 60 | self.error_types = error_types 61 | self.maxfail = maxfail 62 | self.reset_timeout = reset_timeout 63 | self.time_unit = time_unit 64 | self.state = 'closed' 65 | self.last_change = None 66 | self.backoff_cap = backoff_cap 67 | self.test_fail_count = 0 68 | self.with_jitter = with_jitter 69 | self.errors = [] 70 | 71 | def reset(self): 72 | """Reset the breaker after a successful transaction.""" 73 | self.log.info('closing circuit') 74 | self.state = 'closed' 75 | self.test_fail_count = 0 76 | 77 | def open(self, err=None): 78 | self.log.error('got error %r - opening circuit' % (err,)) 79 | self.state = 'open' 80 | self.last_change = self.clock() 81 | 82 | def error(self, err=None): 83 | """Update the circuit breaker with an error event.""" 84 | if self.state == 'half-open': 85 | self.test_fail_count = min(self.test_fail_count + 1, 16) 86 | self.errors.append(self.clock()) 87 | if len(self.errors) > self.maxfail: 88 | time = self.clock() - self.errors.pop(0) 89 | if time < self.time_unit: 90 | if time == 0: 91 | time = 0.0001 92 | self.log.debug('error rate: %f errors per second' % ( 93 | float(self.maxfail) / time)) 94 | self.open(err) 95 | 96 | def test(self): 97 | """Check state of the circuit breaker. 98 | 99 | @raise CircuitOpenError: if the circuit is still open 100 | """ 101 | if self.state == 'open': 102 | delta = self.clock() - self.last_change 103 | 104 | delay_time = self.reset_timeout 105 | if self.backoff_cap: 106 | delay_time = self.reset_timeout * (2 ** self.test_fail_count) 107 | delay_time = min(delay_time, self.backoff_cap) 108 | 109 | if self.with_jitter: 110 | # Add jitter, see: 111 | # http://www.awsarchitectureblog.com/2015/03/backoff.html 112 | delay_time = random.random() * delay_time 113 | 114 | if delta < delay_time: 115 | raise CircuitOpenError() 116 | 117 | self.state = 'half-open' 118 | self.log.debug('half-open - letting one through') 119 | return self.state 120 | 121 | def success(self): 122 | if self.state == 'half-open': 123 | self.reset() 124 | 125 | def __enter__(self): 126 | """Context enter.""" 127 | self.test() 128 | return self 129 | 130 | def __exit__(self, exc_type, exc_val, tb): 131 | """Context exit.""" 132 | if exc_type is None: 133 | self.success() 134 | elif exc_type in self.error_types: 135 | self.error(exc_val) 136 | return False 137 | 138 | 139 | class CircuitBreakerSet(object): 140 | """Controller for a set of circuit breakers. 141 | 142 | @ivar clock: A callable that takes no arguments and return the 143 | current time in seconds. 144 | 145 | @ivar log: A L{logging.Logger} object that is used for the circuit 146 | breakers. 147 | 148 | @ivar maxfail: The maximum number of allowed errors over the 149 | last minute. If the breaker detects more errors than this, the 150 | circuit will open. 151 | 152 | @ivar reset_timeout: Number of seconds to have the circuit open 153 | before it moves into C{half-open}. 154 | """ 155 | 156 | def __init__(self, clock, log, maxfail=3, reset_timeout=10, 157 | time_unit=60, backoff_cap=None, with_jitter=False, 158 | factory=CircuitBreaker): 159 | self.clock = clock 160 | self.log = log 161 | self.maxfail = maxfail 162 | self.reset_timeout = reset_timeout 163 | self.time_unit = time_unit 164 | self.backoff_cap = backoff_cap 165 | self.with_jitter = with_jitter 166 | self.circuits = {} 167 | self.error_types = [] 168 | self.factory = factory 169 | 170 | def handle_error(self, err_type): 171 | """Register error C{err_type} with the circuit breakers so 172 | that it will be handled as an error. 173 | """ 174 | self.error_types.append(err_type) 175 | 176 | def handle_errors(self, err_types): 177 | """Register errors C{err_types} with the circuit breakers so 178 | that it will be handled as an error. 179 | """ 180 | self.error_types.extend(err_types) 181 | 182 | def context(self, id): 183 | """Return a circuit breaker for the given ID.""" 184 | if id not in self.circuits: 185 | self.circuits[id] = self.factory(self.clock, self.log.getChild(id), 186 | self.error_types, self.maxfail, 187 | self.reset_timeout, 188 | self.time_unit, 189 | backoff_cap=self.backoff_cap, 190 | with_jitter=self.with_jitter) 191 | return self.circuits[id] 192 | -------------------------------------------------------------------------------- /circuit/test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edgeware/python-circuit/a40b107e5d539d3118ff495b03aedc08c3d011eb/circuit/test/__init__.py -------------------------------------------------------------------------------- /circuit/test/test_breaker.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012 Edgeware AB. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Test cases for the circuit breaker.""" 16 | 17 | try: 18 | import unittest2 as unittest 19 | except ImportError: 20 | import unittest 21 | 22 | from mockito import mock 23 | 24 | from circuit import breaker, CircuitOpenError 25 | 26 | 27 | class Clock(object): 28 | now = 0.0 29 | 30 | def time(self): 31 | return self.now 32 | 33 | def advance(self, seconds): 34 | self.now += seconds 35 | 36 | 37 | class CircuitBreakerTestCase(unittest.TestCase): 38 | """Test cases for the circuit breaker.""" 39 | 40 | def setUp(self): 41 | self.clock = Clock() 42 | self.log = mock() 43 | self.maxfail = 2 44 | self.reset_timeout = 10 45 | self.time_unit = 60 46 | self.breaker = breaker.CircuitBreaker(self.clock.time, self.log, 47 | [IOError], self.maxfail, 48 | self.reset_timeout, 49 | self.time_unit) 50 | 51 | def test_passes_through_unhandled_errors(self): 52 | try: 53 | with self.breaker: 54 | raise RuntimeError("error") 55 | except RuntimeError: 56 | self.assertEquals(len(self.breaker.errors), 0) 57 | else: 58 | self.assertTrue(False, "exception not raised") 59 | 60 | def test_catches_handled_errors(self): 61 | try: 62 | with self.breaker: 63 | raise IOError("error") 64 | except IOError: 65 | self.assertEquals(len(self.breaker.errors), 1) 66 | else: 67 | self.assertTrue(False, "exception not raised") 68 | 69 | def test_opens_breaker_on_errors(self): 70 | self.breaker.error() 71 | self.breaker.error() 72 | self.breaker.error() 73 | self.assertEquals(self.breaker.state, 'open') 74 | 75 | def test_allows_unfrequent_errors(self): 76 | for i in range(10): 77 | self.breaker.error() 78 | self.clock.advance(30) 79 | self.assertEquals(self.breaker.state, 'closed') 80 | 81 | def test_closes_breaker_on_successful_transaction(self): 82 | self.test_opens_breaker_on_errors() 83 | self.clock.advance(self.reset_timeout) 84 | self.assertEquals(self.breaker.test(), 'half-open') 85 | self.breaker.success() 86 | self.assertEquals(self.breaker.test(), 'closed') 87 | 88 | def test_raises_circuit_open_when_open(self): 89 | self.test_opens_breaker_on_errors() 90 | self.assertRaises(breaker.CircuitOpenError, self.breaker.test) 91 | 92 | def test_context_exit_without_exception_resets_circuit(self): 93 | self.breaker.state = 'half-open' 94 | with self.breaker: 95 | pass 96 | self.assertEquals(self.breaker.state, 'closed') 97 | 98 | def test_context_exit_with_exception_marks_error(self): 99 | def test(): 100 | with self.breaker: 101 | raise IOError("error") 102 | self.assertRaises(IOError, test) 103 | self.assertEquals(len(self.breaker.errors), 1) 104 | 105 | def test_exponential_backoff_timeout(self): 106 | self.breaker = breaker.CircuitBreaker(self.clock.time, self.log, 107 | [IOError], self.maxfail, 108 | self.reset_timeout, 109 | self.time_unit, 110 | 64, with_jitter=False) 111 | 112 | # Test that the failure after first reset_timeout * 1 bumps the 113 | # failure counter 114 | self.test_opens_breaker_on_errors() 115 | self.clock.advance(self.reset_timeout) 116 | self.assertEquals(self.breaker.test(), 'half-open') 117 | self.breaker.error() 118 | self.assertEquals(self.breaker.test_fail_count, 1) 119 | 120 | # Test that it does not recover before the 2 ** 1 * reset_timeout 121 | # period 122 | self.clock.advance(self.reset_timeout) 123 | raised_e = None 124 | try: 125 | self.breaker.test() 126 | except CircuitOpenError as e: 127 | raised_e = e 128 | self.assertIsNotNone(raised_e) 129 | self.assertEquals(self.breaker.test_fail_count, 1) 130 | 131 | # test that after the 2 ** 1 * reset_timeout the circuit half-opens 132 | self.clock.advance(self.reset_timeout) 133 | self.assertEquals(self.breaker.test(), 'half-open') 134 | 135 | # then another error bumps up the fail counter again 136 | self.breaker.error() 137 | self.assertEquals(self.breaker.test_fail_count, 2) 138 | self.clock.advance(self.reset_timeout) 139 | self.breaker.error() 140 | self.assertEquals(self.breaker.test_fail_count, 2) 141 | 142 | self.clock.advance(self.reset_timeout * 4) 143 | self.assertEquals(self.breaker.test(), 'half-open') 144 | self.breaker.success() 145 | self.assertEquals(self.breaker.test_fail_count, 0) 146 | 147 | def test_backoff_with_jitter(self): 148 | self.breaker = breaker.CircuitBreaker(self.clock.time, self.log, 149 | [IOError], self.maxfail, 150 | self.reset_timeout, 151 | self.time_unit, 152 | 64, with_jitter=True) 153 | self.test_opens_breaker_on_errors() 154 | self.clock.advance(self.reset_timeout) 155 | self.breaker.test() 156 | self.breaker.error() 157 | self.assertEquals(self.breaker.test_fail_count, 1) 158 | self.clock.advance(self.reset_timeout * 2) 159 | self.breaker.test() 160 | self.breaker.error() 161 | self.assertEquals(self.breaker.test_fail_count, 2) 162 | # Should have a reset_time of: 163 | # [0, 4 * reset_timeout] * random.random(), mean = 2 * reset_timeout. 164 | # 99th percentile value of count of failures 165 | failure_count = 0 166 | self.clock.advance(self.reset_timeout * 2) 167 | for _ in range(1000): 168 | try: 169 | self.breaker.test() 170 | self.breaker.open() 171 | self.clock.advance(self.reset_timeout * 2) 172 | except CircuitOpenError: 173 | failure_count += 1 174 | 175 | # .999999999 chance of falling in this range 176 | self.assertGreater(failure_count, 400) 177 | 178 | self.assertLess(failure_count, 600) 179 | -------------------------------------------------------------------------------- /circuit/test/test_twisted.py: -------------------------------------------------------------------------------- 1 | # Copyright 2012 Edgeware AB. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from mockito import mock, when 16 | import unittest 17 | 18 | from twisted.internet import task, defer 19 | 20 | from circuit import TwistedCircuitBreakerSet 21 | 22 | 23 | class TwistedCircuitBreakerTestCase(unittest.TestCase): 24 | 25 | def setUp(self): 26 | self.clock = task.Clock() 27 | self.log = mock() 28 | when(self.log).getChild('ctxt').thenReturn(self.log) 29 | self.circuit_breaker = TwistedCircuitBreakerSet(self.clock, self.log) 30 | 31 | def test_context_exit_with_inline_callbacks_resets_circuit(self): 32 | @defer.inlineCallbacks 33 | def test(): 34 | with self.circuit_breaker.context('ctxt') as breaker: 35 | breaker.state = 'half-open' 36 | yield defer.succeed(None) 37 | defer.returnValue(None) 38 | test() 39 | self.assertEquals(self.circuit_breaker.circuits['ctxt'].state, 40 | 'closed') 41 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | 4 | from setuptools import setup 5 | 6 | with open('README.md') as f: 7 | long_description = f.read().strip() 8 | 9 | tests_require = [ 10 | 'mockito==0.6.0', 11 | ] 12 | 13 | if sys.version_info < (2, 7): 14 | tests_require.append('unittest2') 15 | tests_require.append('Twisted>=10.2,<15.5') # py2.6 support was dropped in 15.5 16 | else: 17 | tests_require.append('Twisted>=10.2') 18 | 19 | setup(name='python-circuit', 20 | version='0.1.9', 21 | description='Simple implementation of the Circuit Breaker pattern', 22 | long_description=long_description, 23 | author='Edgeware', 24 | author_email='info@edgeware.tv', 25 | url='https://github.com/edgeware/python-circuit', 26 | license='Apache v2.0 License', 27 | packages=['circuit'], 28 | test_suite='circuit.test', 29 | tests_require=tests_require) 30 | --------------------------------------------------------------------------------