├── LICENSE ├── README.md ├── conf └── beholder.yml ├── scripts └── beholder.init └── src └── beholder.py /LICENSE: -------------------------------------------------------------------------------- 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. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Beholder 2 | 3 | Beholder is an agent written in [Python](https://www.python.org/) for [twemproxy](https://github.com/twitter/twemproxy) to work with a [redis sentinel](http://redis.io/topics/sentinel) to provide support for failover. 4 | 5 | Beholder's purpose is to extend the HA capabilities of twemproxy even after a redis node has failed. 6 | 7 | In order to accomplish this, beholder is continuously monitoring the **+switch-master** event, then it will update twemproxy configuration files and restart the resource. 8 | 9 | ## Dependencies 10 | 11 | Beholder use [redis-py](https://github.com/andymccurdy/redis-py) and [pyyaml](http://pyyaml.org/), so the first step is install the dependencies: 12 | 13 | $ pip install redis 14 | $ pip install pyyaml 15 | 16 | If you want to install python yaml system-wide in linux, you can also use a package manager, like: 17 | 18 | $ sudo apt-get install python-yaml 19 | $ sudo yum install python-yaml 20 | 21 | ## Installation 22 | 23 | The follow installation steps are the default ones, feel free to change any path. 24 | 25 | $ sudo cp src/beholder.py /usr/local/bin/beholder.py 26 | $ sudo cp conf/beholder.yml /etc/nutcracker/beholder.yml 27 | $ sudo cp scripts/beholder.init /etc/init.d/beholder 28 | $ sudo chmod 775 /etc/init.d/beholder 29 | $ sudo chkconfig --add /etc/init.d/beholder 30 | $ sudo chkconfig beholder on 31 | $ sudo service beholder start 32 | 33 | ## Configuration 34 | 35 | Beholder can be configured through a YAML file [beholder.yml](config/beholder.yml). 36 | 37 | beholder: 38 | log_file: "/var/log/beholder.log" 39 | connect_retry_count: -1 # -1 to unlimited 40 | connect_retry_interval: 1000 # Milliseconds 41 | 42 | redis: 43 | sentinel_ip: "127.0.0.1" 44 | sentinel_port: 26379 45 | 46 | twemproxy: 47 | config_file: "/etc/nutcracker/nutcracker.yml" 48 | restart_command: "/etc/init.d/nutcracker restart" 49 | 50 | ## Contributing 51 | 52 | 1. Fork it 53 | 2. Create your feature branch (`git checkout -b my-new-feature`) 54 | 3. Commit your changes (`git commit -am 'Add some feature'`) 55 | 4. Push to the branch (`git push origin my-new-feature`) 56 | 5. Create new Pull Request 57 | 58 | ## License 59 | 60 | Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 61 | 62 | See [LICENSE.md](LICENSE) -------------------------------------------------------------------------------- /conf/beholder.yml: -------------------------------------------------------------------------------- 1 | beholder: 2 | log_file: "/var/log/beholder.log" 3 | connect_retry_count: -1 # -1 to unlimited 4 | connect_retry_interval: 1000 # Milliseconds 5 | 6 | redis: 7 | sentinel_ip: "127.0.0.1" 8 | sentinel_port: 26379 9 | 10 | twemproxy: 11 | config_file: "/etc/nutcracker/nutcracker.yml" 12 | restart_command: "/etc/init.d/nutcracker restart" 13 | -------------------------------------------------------------------------------- /scripts/beholder.init: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Simple Beholder init.d script conceived to work on Linux systems 4 | # as it does use of the /proc filesystem. 5 | # chkconfig: - 15 80 6 | # description: Beholder service 7 | 8 | EXEC=/usr/local/bin/beholder.py 9 | 10 | PIDFILE=/var/run/beholder.pid 11 | CONF="/etc/nutcracker/beholder.yml" 12 | 13 | case "$1" in 14 | start) 15 | if [ -f $PIDFILE ] 16 | then 17 | echo "$PIDFILE exists, process is already running or crashed" 18 | else 19 | echo "Starting Beholder..." 20 | python $EXEC $PIDFILE $CONF > /dev/null 2>&1 & 21 | fi 22 | ;; 23 | stop) 24 | if [ ! -f $PIDFILE ] 25 | then 26 | echo "$PIDFILE does not exist, process is not running" 27 | else 28 | PID=$(cat $PIDFILE) 29 | echo "Stopping ..." 30 | kill ${PID} 31 | while [ -x /proc/${PID} ] 32 | do 33 | echo "Waiting for Beholder to shutdown ..." 34 | sleep 1 35 | done 36 | echo "Beholder stopped" 37 | fi 38 | ;; 39 | *) 40 | echo "Please use start or stop as first argument" 41 | ;; 42 | esac 43 | 44 | -------------------------------------------------------------------------------- /src/beholder.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import time 4 | import signal 5 | import threading 6 | import logging 7 | import logging.handlers 8 | import yaml 9 | import redis 10 | 11 | 12 | class PidfileHelper(object): 13 | def __init__(self, pidfile): 14 | self._pidfile = pidfile 15 | 16 | def exist(self): 17 | """ Check for a pidfile to see if the daemon already runs """ 18 | b_exist = True 19 | try: 20 | with open(self._pidfile, 'r') as pf: 21 | pid = int(pf.read().strip()) 22 | except IOError: 23 | b_exist = False 24 | return b_exist 25 | 26 | def create(self): 27 | """ Create the pidfile """ 28 | pid = str(os.getpid()) 29 | with open(self._pidfile, 'w+') as f: 30 | f.write(pid + '\n') 31 | return pid 32 | 33 | def delete(self): 34 | """ Remove the pidfile """ 35 | os.remove(self._pidfile) 36 | 37 | 38 | class BeholderConfig(object): 39 | def __init__(self, config_filename): 40 | with open(config_filename) as f: 41 | config_data = yaml.safe_load(f) 42 | self.beholder_log_file = config_data['beholder']['log_file'] 43 | self.beholder_connect_retry_count = config_data['beholder']['connect_retry_count'] 44 | self.beholder_connect_retry_interval = config_data['beholder']['connect_retry_interval'] 45 | self.redis_sentinel_ip = config_data['redis']['sentinel_ip'] 46 | self.redis_sentinel_port = config_data['redis']['sentinel_port'] 47 | self.twemproxy_config_file = config_data['twemproxy']['config_file'] 48 | self.twemproxy_restart_command = config_data['twemproxy']['restart_command'] 49 | 50 | 51 | class BeholderLogger(object): 52 | def __init__(self, name, log_filename): 53 | # Create logger 54 | self._logger = logging.getLogger(name) 55 | self._logger.setLevel(logging.INFO) 56 | # Create file handler 57 | handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=524288, backupCount=3) 58 | handler.setLevel(logging.INFO) 59 | # Create formatter 60 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 61 | # Configure logger 62 | handler.setFormatter(formatter) 63 | self._logger.addHandler(handler) 64 | 65 | def debug(self, msg): 66 | self._logger.debug(msg) 67 | 68 | def info(self, msg): 69 | self._logger.info(msg) 70 | 71 | def warning(self, msg): 72 | self._logger.warning(msg) 73 | 74 | def error(self, msg): 75 | self._logger.error(msg) 76 | 77 | def critical(self, msg): 78 | self._logger.critical(msg) 79 | 80 | def exception(self, msg): 81 | self._logger.exception(msg) 82 | 83 | 84 | class Beholder(object): 85 | def __init__(self, pid, config_filename): 86 | self._config = BeholderConfig(config_filename) 87 | self._logger = BeholderLogger(pid, self._config.beholder_log_file) 88 | self._stop_event = threading.Event() 89 | signal.signal(signal.SIGTERM, self._signal_termination_handler) 90 | self._pubsub = None 91 | 92 | def __del__(self): 93 | if self._pubsub is not None: 94 | self._pubsub.close() 95 | 96 | def execute(self): 97 | if self._connect(): 98 | while not self._stop_event.is_set(): 99 | message = self._pubsub.get_message() 100 | if message and message['type'] == 'message': 101 | switch_master_info = str(message['data']).split(' ') 102 | self._switch_master(switch_master_info) 103 | time.sleep(0.001) 104 | self._logger.info('Beholder stopped') 105 | 106 | def _signal_termination_handler(self, signaum, frame): 107 | """ Listen SIGTERM signal to stop the process in the right way """ 108 | self._logger.info('Signal.SIGTERM received') 109 | self._stop_event.set() 110 | 111 | def _connect(self): 112 | """ Connect to Redis sentinel and subscribe to the channel '+switch-master' to listen master changes """ 113 | b_connected = False 114 | retry_count = 0 115 | while not self._stop_event.is_set() and not b_connected: 116 | try: 117 | self._redis = redis.StrictRedis(host=self._config.redis_sentinel_ip, port=self._config.redis_sentinel_port) 118 | self._pubsub = self._redis.pubsub() 119 | self._pubsub.subscribe(['+switch-master']) 120 | except: 121 | self._logger.exception('Redis sentinel connection error: %s' % retry_count) 122 | # Check if maximum retry count is arrived 123 | if self._config.beholder_connect_retry_count > 0 and retry_count >= self._config.beholder_connect_retry_count: 124 | self._stop_event.set() 125 | self._logger.critical('Max retries exceeded') 126 | else: 127 | retry_count += 1 128 | time.sleep(self._config.beholder_connect_retry_interval / 1000) 129 | else: 130 | b_connected = True 131 | 132 | return b_connected 133 | 134 | def _switch_master(self, switch_master_info): 135 | """ Called when new message is publish in the sentinel channel (+switch-master) """ 136 | if len(switch_master_info) > 3: 137 | old_ip = switch_master_info[1] 138 | old_port = switch_master_info[2] 139 | new_ip = switch_master_info[3] 140 | new_port = switch_master_info[4] 141 | if self._update_masters(old_ip, old_port, new_ip, new_port): 142 | self._restart_twemproxy() 143 | self._logger.info('Master changed successfully') 144 | else: 145 | err = 'Master update error (%s:%s --> %s:%s)' % (old_ip, old_port, new_ip, new_port) 146 | self._logger.error(err) 147 | else: 148 | self._logger.warning('Wrong number of parameters: %s' % switch_master_info) 149 | 150 | def _update_masters(self, old_server, old_port, new_server, new_port): 151 | """ Updates the address of a server in the twemproxy config """ 152 | b_updated = False 153 | 154 | try: 155 | with open(self._config.twemproxy_config_file) as f: 156 | proxy_data = yaml.safe_load(f) 157 | except: 158 | self._logger.exception('Could not open the twemproxy configuration file') 159 | else: 160 | for proxy in proxy_data: 161 | for i, server in enumerate(proxy_data[proxy]['servers']): 162 | server_data = server.split(' ') 163 | url_data = server_data[0].split(':') 164 | 165 | host = url_data[0] 166 | port = url_data[1] 167 | number = url_data[2] 168 | name = '' 169 | 170 | try: 171 | name = server_data[1] 172 | except: 173 | pass 174 | 175 | # Check if the current server is the old master server 176 | if str(host) == str(old_server) and str(port) == str(old_port): 177 | host = new_server 178 | port = new_port 179 | proxy_data[proxy]['servers'][i]= host + ':' + str(port) + ':' + str(number) + ' ' + name 180 | self._logger.info('%s -> %s:%s changed to %s:%s' % (name, old_server, old_port, host, port)) 181 | b_updated = True 182 | 183 | try: 184 | with open(self._config.twemproxy_config_file, 'w') as f: 185 | yaml.dump(proxy_data, f, default_flow_style=False) 186 | except: 187 | self._logger.warning('Could not updated the twemproxy configuration file') 188 | b_updated = False 189 | 190 | return b_updated 191 | 192 | def _restart_twemproxy(self): 193 | """ Restart Twemproxy/Nutcracker service to reload the changes in configuration files """ 194 | os.system(self._config.twemproxy_restart_command) 195 | 196 | if __name__ == "__main__": 197 | pidfile = sys.argv[1] # '/var/run/beholder.pid' 198 | config = sys.argv[2] # 'beholder.yml' 199 | 200 | pidfile_helper = PidfileHelper(pidfile) 201 | if not pidfile_helper.exist(): 202 | try: 203 | pid = pidfile_helper.create() 204 | beholder = Beholder(pid, config) 205 | beholder.execute() 206 | finally: 207 | pidfile_helper.delete() 208 | sys.exit(0) 209 | else: 210 | sys.exit(1) --------------------------------------------------------------------------------