├── runtime.txt ├── static ├── css │ └── mystyle.css └── js │ └── redis.js ├── Dockerfile ├── Makefile ├── README.md ├── manifest.yml ├── requirements.txt ├── k8s └── deployment.yaml ├── .gitignore ├── tests └── test_app.py ├── templates └── index.html ├── config.py ├── app.py └── LICENSE /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.18 -------------------------------------------------------------------------------- /static/css/mystyle.css: -------------------------------------------------------------------------------- 1 | div.content-flow { 2 | overflow-y: auto; 3 | width: 100%; 4 | height: 300px; 5 | } 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8 2 | 3 | ENV FLASK_APP app.py 4 | ENV APP_SETTINGS settings.cfg 5 | ENV NO_URL_QUOTING True 6 | COPY . /app 7 | WORKDIR /app 8 | 9 | RUN pip install -r requirements.txt 10 | 11 | RUN make memtier_benchmark 12 | 13 | CMD python -m flask run -p 8080 -h 0.0.0.0 14 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: push 2 | push: memtier_benchmark 3 | cf push 4 | 5 | memtier_benchmark: 6 | wget https://s3.eu-central-1.amazonaws.com/redislabs-dev-public-deps/binaries/memtier_benchmark_1.2.15_xenial 7 | mv memtier_benchmark_1.2.15_xenial memtier_benchmark 8 | chmod +x memtier_benchmark 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Docker Pulls](https://img.shields.io/docker/pulls/redislabs/redis-webcli)](https://hub.docker.com/r/redislabs/redis-webcli) 2 | 3 | # redis-webcli 4 | 5 | A tiny Flask app to provide access to Redis through a web form. 6 | 7 | ## PCF Installation instructions 8 | 9 | You need to have cf-cli installed. After having cf-cli installed, just run `make push` 10 | -------------------------------------------------------------------------------- /manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: redis-webcli 4 | memory: 128MB 5 | disk_quota: 256MB 6 | random-route: true 7 | buildpacks: 8 | - https://github.com/cloudfoundry/python-buildpack.git#v1.8.15 9 | command: python -m flask run -p $PORT -h 0.0.0.0 10 | env: 11 | FLASK_APP: app.py 12 | APP_SETTINGS: settings.cfg 13 | NO_URL_QUOTING: True 14 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flask==3.0.3 2 | flask_redis==0.4.0 3 | flask_redis_sentinel==2.0.1 4 | flask_bootstrap==3.3.7.1 5 | async-timeout==4.0.3 6 | blinker==1.8.1 7 | click==8.1.7 8 | dominate==2.9.1 9 | importlib_metadata==7.1.0 10 | itsdangerous==2.2.0 11 | Jinja2==3.1.4 12 | MarkupSafe==2.1.5 13 | pip==23.0.1 14 | redis==5.0.4 15 | Redis-Sentinel-Url==1.0.1 16 | setuptools==57.5.0 17 | six==1.16.0 18 | visitor==0.1.3 19 | Werkzeug==3.0.3 20 | wheel==0.43.0 21 | zipp==3.18.1 22 | -------------------------------------------------------------------------------- /k8s/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: redis-webcli 5 | spec: 6 | replicas: 1 7 | selector: 8 | matchLabels: 9 | name: redis-webcli 10 | app: redis-webcli 11 | template: 12 | metadata: 13 | labels: 14 | name: redis-webcli 15 | app: redis-webcli 16 | spec: 17 | containers: 18 | - name: redis-webcli 19 | image: redislabs/redis-webcli:latest 20 | imagePullPolicy: Always 21 | env: 22 | - name: REDIS_SENTINEL_HOST 23 | value: redis-enterprise 24 | - name: REDIS_SENTINEL_PORT 25 | value: "8001" 26 | - name: REDIS_PASSWORD 27 | value: "" 28 | - name: REDIS_DBNAME 29 | value: demo 30 | --- 31 | kind: Service 32 | apiVersion: v1 33 | metadata: 34 | name: redis-webcli 35 | spec: 36 | type: LoadBalancer 37 | selector: 38 | name: redis-webcli 39 | app: redis-webcli 40 | ports: 41 | - protocol: TCP 42 | port: 8080 43 | targetPort: 8080 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # intellij files 2 | .idea 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # dotenv 86 | .env 87 | 88 | # virtualenv 89 | .venv 90 | venv/ 91 | ENV/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /tests/test_app.py: -------------------------------------------------------------------------------- 1 | import app 2 | import os 3 | 4 | 5 | def test_configure(): 6 | os.environ["REDIS_SENTINEL_HOST"] = "10.128.0.226,10.129.3.16,10.130.0.135,10.130.0.13,10.129.0.135" 7 | os.environ["REDIS_SENTINEL_PORT"] = "8001" 8 | os.environ["REDIS_PASSWORD"] = "automation" 9 | os.environ["REDIS_DBNAME"] = "bdb-test" 10 | 11 | app.configure() 12 | assert app.app.config['REDIS_URL'] == "redis+sentinel://:automation@10.128.0.226:8001," \ 13 | "10.129.3.16:8001,10.130.0.135:8001,10.130.0.13:8001,10.129.0.135:8001" \ 14 | "/bdb-test/0" 15 | 16 | 17 | def test_vcap_configure(): 18 | os.environ = dict() 19 | os.environ["VCAP_SERVICES"] = """{ 20 | "redislabs": [ 21 | { 22 | "label": "redislabs", 23 | "provider": null, 24 | "plan": "medium-redis", 25 | "name": "redis-webcli-service-NRY6IA75", 26 | "tags": [ 27 | "redislabs", 28 | "redis" 29 | ], 30 | "instance_name": "redis-webcli-service-NRY6IA75", 31 | "binding_name": null, 32 | "credentials": { 33 | "host": "redis-1071.c1.sys.testpcfb7d42.qa.redislabs.com", 34 | "sentinel_addrs": ["10.128.0.226","10.129.3.16","10.130.0.135","10.130.0.13","10.129.0.135"], 35 | "sentinel_port": 8001, 36 | "ip_list": [ 37 | "10.0.4.21" 38 | ], 39 | "name": "redis-webcli-db-NRY6IA75", 40 | "password": "iGBnw-An_owEKhkoEMwdni7mnX_qHBSfyZc31AbbYlGqyE0x", 41 | "port": 1071 42 | }, 43 | "syslog_drain_url": null, 44 | "volume_mounts": [] 45 | } 46 | ] 47 | } 48 | """ 49 | os.environ["NO_URL_QUOTING"] = True 50 | app.configure() 51 | assert app.app.config['REDIS_URL'] == "redis+sentinel://:iGBnw-An_owEKhkoEMwdni7mnX_qHBSfyZc31AbbYlGqyE0x@10.128.0.226:8001," \ 52 | "10.129.3.16:8001,10.130.0.135:8001,10.130.0.13:8001,10.129.0.135:8001" \ 53 | "/redis-webcli-db-NRY6IA75/0" 54 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "bootstrap/base.html" %} 2 | {% block title %}Redis Web-Based Interface{% endblock %} 3 | 4 | {% block scripts %} 5 | {{ super() }} 6 | 7 | {% endblock %} 8 | 9 | {% block styles %} 10 | {{super()}} 11 | 12 | {% endblock %} 13 | 14 | {% block content %} 15 |
16 |
17 |

Redis CLI

18 |
19 |
20 |
Connection
21 |
22 | {% for key, value in conninfo %} 23 |
24 |
{{ key }}
25 |
{{ value }}
26 |
27 | {% endfor %} 28 |
29 |
30 |
31 |
Redis CLI
32 |
33 |
34 | 35 | 36 | 37 | 38 |
39 |

40 |

41 |

42 |           
43 |
44 |
45 |
46 |
Sentinel
47 |
48 |
49 | 50 |
51 |

52 |

53 |

54 |               
55 |
56 |
57 |
58 |
Memtier Benchmark
59 |
60 |
61 | 62 | 63 | 64 | 65 | 66 | 67 |
68 |

69 |

70 |

71 |               
72 |
73 |
74 |
75 | {% endblock %} 76 | -------------------------------------------------------------------------------- /static/js/redis.js: -------------------------------------------------------------------------------- 1 | function set_response(resp) { 2 | $('#response').text(resp + "\n"); 3 | } 4 | 5 | $("#execute").click(function() { 6 | $(this).button("loading"); 7 | $.ajax({ 8 | type: "post", 9 | url: "/execute", 10 | dataType: "json", 11 | contentType: "application/json; charset=utf-8", 12 | data: JSON.stringify({command: $("#command").val()}), 13 | error: function(xhr, status, msg) { 14 | $("#execute").button("reset"); 15 | set_response("ERROR: " + msg); 16 | }, 17 | success: function(resp) { 18 | set_response(resp.response); 19 | $("#execute").button("reset"); 20 | } 21 | }) 22 | }) 23 | 24 | function set_masters_response(resp) { 25 | $('#masters_response').text(resp + "\n"); 26 | } 27 | 28 | $("#masters").click(function() { 29 | $(this).button("loading"); 30 | $.ajax({ 31 | type: "get", 32 | url: "/masters", 33 | error: function(xhr, status, msg) { 34 | $("#masters").button("reset"); 35 | set_masters_response("ERROR: " + msg); 36 | }, 37 | success: function(resp) { 38 | let value = "Host: " + resp.response[0] + " Port: " + resp.response[1] 39 | set_masters_response(value); 40 | $("#masters").button("reset"); 41 | } 42 | }) 43 | }) 44 | 45 | function set_memtier_response(resp) { 46 | $('#memtier_response').text(resp + "\n"); 47 | } 48 | 49 | $("#memtier_start").click(function() { 50 | $("#memtier_start").button("loading"); 51 | set_memtier_response(""); 52 | $.ajax({ 53 | type: "post", 54 | url: "/memtier_benchmark/start", 55 | dataType: "json", 56 | contentType: "application/json; charset=utf-8", 57 | data: JSON.stringify({args: $("#arguments").val()}), 58 | error: function(xhr, status, msg) { 59 | $("#memtier_start").button("reset"); 60 | set_memtier_response("ERROR: " + msg); 61 | }, 62 | success: function(resp) { 63 | set_memtier_response(resp.response); 64 | } 65 | }) 66 | }) 67 | 68 | $("#memtier_poll").click(function() { 69 | $("#memtier_poll").button("loading"); 70 | set_memtier_response(""); 71 | $.ajax({ 72 | type: "get", 73 | url: "/memtier_benchmark/poll", 74 | error: function(xhr, status, msg) { 75 | $("#memtier_poll").button("reset"); 76 | $("#memtier_start").button("reset"); 77 | set_memtier_response("ERROR: " + msg); 78 | }, 79 | success: function(resp) { 80 | set_memtier_response(resp.response[1]); 81 | $("#memtier_poll").button("reset"); 82 | if (resp.response[0]) { 83 | $("#memtier_start").button("reset"); 84 | } 85 | } 86 | }) 87 | }) 88 | 89 | $("#memtier_stop").click(function() { 90 | $("#memtier_stop").button("loading"); 91 | set_memtier_response(""); 92 | $.ajax({ 93 | type: "post", 94 | url: "/memtier_benchmark/stop", 95 | error: function(xhr, status, msg) { 96 | $("#memtier_stop").button("reset"); 97 | set_memtier_response("ERROR: " + msg); 98 | }, 99 | success: function(resp) { 100 | set_memtier_response(resp.response); 101 | $("#memtier_stop").button("reset"); 102 | $("#memtier_start").button("reset"); 103 | } 104 | }) 105 | }) 106 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import logging 4 | try: 5 | # Python 2.x 6 | from urllib import quote 7 | except ImportError: 8 | # Python 3.x 9 | from urllib.parse import quote 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | def configure(app): 14 | # Let Redis decode responses from bytes to strings 15 | app.config['REDIS_DECODE_RESPONSES'] = True 16 | redis_password = os.getenv('REDIS_PASSWORD') 17 | redis_username = os.getenv('REDIS_USERNAME') 18 | redis_dbname = None 19 | sentinel_addr = None 20 | sentinel_port = None 21 | 22 | if should_read_from_file_system(): 23 | redis_username, redis_password = get_username_and_password_from_file_system() 24 | if not redis_password: 25 | logger.error("Couldn't read redis password from file system.") 26 | return 27 | 28 | # Handle Cloud Foundry with Sentinel 29 | if 'VCAP_SERVICES' in os.environ: 30 | services = json.loads(os.getenv('VCAP_SERVICES')) 31 | service = _get_service(services) 32 | creds = service['credentials'] 33 | redis_password = creds['password'] 34 | redis_dbname = quote(creds['name'], safe='') 35 | 36 | if 'sentinel_addrs' in creds: 37 | sentinel_addr = creds['sentinel_addrs'] 38 | sentinel_port = creds['sentinel_port'] 39 | else: 40 | sentinel_addr = os.getenv('REDIS_SENTINEL_HOST').split(",") # example: 1.1.1.1,2.2.2.2 41 | sentinel_port = os.getenv('REDIS_SENTINEL_PORT') 42 | 43 | elif 'REDIS_SENTINEL_HOST' in os.environ: 44 | redis_dbname = os.getenv('REDIS_DBNAME') 45 | sentinel_addr = os.getenv('REDIS_SENTINEL_HOST').split(",") 46 | sentinel_port = os.getenv('REDIS_SENTINEL_PORT') 47 | else: 48 | logger.warning("Couldn't configure redis") 49 | return 50 | 51 | if not os.getenv('NO_URL_QUOTING'): 52 | redis_password = quote(redis_password, safe='') 53 | sentinel_host = ",".join("%s:%s" % (addr, sentinel_port) for addr in sentinel_addr) 54 | app.config['REDIS_URL'] = 'redis+sentinel://:%s@%s/%s/0' % ( 55 | redis_password, 56 | sentinel_host, 57 | redis_dbname) 58 | app.config['REDIS_PASSWORD'] = redis_password 59 | app.config['REDIS_USERNAME'] = redis_username 60 | app.config['SSL_ENABLED'] = get_boolean_val_from_env('REDIS_WEBCLI_SSL_ENABLED', 61 | False) 62 | app.config['SKIP_HOSTNAME_VALIDATION'] = \ 63 | get_boolean_val_from_env('REDIS_WEBCLI_SKIP_HOSTNAME_VALIDATION', 64 | False) 65 | app.config['USE_SENTINEL'] = get_boolean_val_from_env('USE_SENTINEL', True) 66 | app.config['DB_SERVICE_HOST'] = os.getenv('DB_SERVICE_HOST') 67 | app.config['DB_SERVICE_PORT'] = os.getenv('DB_SERVICE_PORT') 68 | 69 | 70 | def should_read_from_file_system(): 71 | return get_boolean_val_from_env('READ_FROM_FILE_SYSTEM', False) 72 | 73 | def get_username_and_password_from_file_system(): 74 | file_system_location = os.getenv('FILE_SYSTEM_LOCATION') 75 | redis_password = None 76 | redis_username = None 77 | if not file_system_location: 78 | logger.error("Missing FILE_SYSTEM_LOCATION from env variable.") 79 | else: 80 | try: 81 | with open(file_system_location) as json_file: 82 | credentials = json.load(json_file) 83 | redis_password = credentials['password'] 84 | redis_username = credentials['username'] 85 | 86 | except (FileNotFoundError, ValueError, KeyError): 87 | logger.error("Couldn't parse vault file %s", file_system_location) 88 | 89 | return redis_username, redis_password 90 | 91 | def get_boolean_val_from_env(env_entry_name, default_value): 92 | val = os.getenv(env_entry_name) 93 | if val is None: 94 | return default_value 95 | 96 | if val.lower() == "true": 97 | return True 98 | 99 | if val.lower() == "false": 100 | return False 101 | 102 | logger.warning("ignoring value for: %s, should be either true/false", env_entry_name) 103 | return default_value 104 | 105 | def _get_service(services): 106 | for service_name, instances in services.items(): 107 | for instance in instances: 108 | if 'redis' in instance.get('tags', []): 109 | return instance 110 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import threading 3 | import time 4 | import subprocess 5 | import json 6 | try: 7 | # Python 2.x 8 | from urlparse import urlparse 9 | from urllib import quote 10 | except ImportError: 11 | # Python 3.x 12 | from urllib.parse import urlparse, quote 13 | from flask import Flask, render_template, request, jsonify, abort 14 | from flask import current_app as capp 15 | from flask_redis_sentinel import SentinelExtension 16 | import flask_redis_sentinel 17 | from flask_bootstrap import Bootstrap 18 | from config import configure, should_read_from_file_system, get_username_and_password_from_file_system 19 | import redis_sentinel_url 20 | import redis 21 | 22 | 23 | class MyOverride(object): 24 | @classmethod 25 | def _my_config_from_variables(cls, config, the_class): 26 | args = inspect.getfullargspec(the_class.__init__).args 27 | args.remove('self') 28 | args.remove('host') 29 | args.remove('port') 30 | args.remove('db') 31 | return {arg: config[arg.upper()] for arg in args if arg.upper() in config} 32 | 33 | flask_redis_sentinel.RedisSentinel._config_from_variables = MyOverride._my_config_from_variables 34 | redis_sentinel = SentinelExtension() 35 | sentinel = redis_sentinel.sentinel 36 | 37 | 38 | app = Flask(__name__) 39 | 40 | configure(app) 41 | redis_sentinel.init_app(app) 42 | Bootstrap(app) 43 | # print("done") 44 | 45 | 46 | class MemtierThread(threading.Thread): 47 | def __init__(self, master_ip, master_port, redis_password=None, argument_line="", **kwargs): 48 | try: 49 | # Python 3.x 50 | super().__init__(**kwargs) 51 | except TypeError: 52 | # Python 2.x 53 | super(MemtierThread, self).__init__(**kwargs) 54 | self._master_ip = master_ip 55 | self._master_port = master_port 56 | self._redis_password = redis_password 57 | self._argument_list = argument_line.split() 58 | self._output = "" 59 | self._return_code = None 60 | self._process = None 61 | 62 | def run(self): 63 | self._process = subprocess.Popen(["./memtier_benchmark", "-s", self._master_ip, "-p", self._master_port, "-a", self._redis_password] + self._argument_list, 64 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, shell=False) 65 | while True: 66 | curr_output = self._process.stdout.readline().decode("utf-8") 67 | if "[RUN" in curr_output: 68 | temp_output = curr_output.split("[RUN") 69 | curr_output = "\n[RUN".join(temp_output) 70 | if curr_output == '': 71 | self._return_code = self._process.poll() 72 | if self._return_code != None: 73 | return 74 | if curr_output: 75 | self._output = self._output + "\n" + curr_output.strip() 76 | 77 | def kill(self): 78 | if self._process: 79 | self._process.kill() 80 | self.join() 81 | self._process = None 82 | 83 | @property 84 | def output(self): 85 | return self._output 86 | 87 | @property 88 | def return_code(self): 89 | return self._return_code 90 | 91 | 92 | def _get_request_json(): 93 | if request.is_json: 94 | return request.get_json() 95 | data = request.data 96 | if isinstance(data, bytes): 97 | data = data.decode('utf-8') 98 | return json.loads(data) 99 | 100 | 101 | def _execute(command: str): 102 | success = False 103 | try: 104 | conn = get_conn() 105 | response = conn.execute_command(*command.split()) 106 | success = True 107 | except (redis.exceptions.ConnectionError, redis.exceptions.ResponseError): 108 | try: 109 | reload_username_password_from_file_system_if_needed(app) 110 | conn = get_conn() 111 | response = conn.execute_command(*command.split()) 112 | success = True 113 | except Exception as err: 114 | response = 'Exception: cannot connect. %s' % str(err) 115 | app.logger.exception("execute err") 116 | except Exception as err: 117 | response = 'Exception: %s' % str(err) 118 | app.logger.exception("execute err") 119 | return response, success 120 | 121 | 122 | @app.route('/execute', methods=['POST']) 123 | def execute(): 124 | try: 125 | req = _get_request_json() 126 | except Exception as err: 127 | app.logger.exception("_get_request_json err") 128 | return jsonify({ 129 | 'response': 'Exception: %s' % str(err), 130 | 'success': False 131 | }) 132 | 133 | response, success = _execute(req['command']) 134 | 135 | return jsonify({ 136 | 'response': response, 137 | 'success': success 138 | }) 139 | 140 | 141 | @app.route('/batch_execute', methods=['POST']) 142 | def batch_execute(): 143 | all_succeeded = True 144 | responses = [] 145 | try: 146 | req = _get_request_json() 147 | except Exception as err: 148 | app.logger.exception("_get_request_json err") 149 | return jsonify({ 150 | 'response': 'Exception: %s' % str(err), 151 | 'success': False 152 | }) 153 | 154 | commands = req['commands'] 155 | for command in commands: 156 | response, success = _execute(command) 157 | responses.append({ 158 | 'response': response, 159 | 'success': success, 160 | }) 161 | if not success: 162 | all_succeeded = False 163 | return jsonify({ 164 | 'response': responses, 165 | 'success': all_succeeded 166 | }) 167 | 168 | 169 | def reload_username_password_from_file_system_if_needed(app): 170 | # It may be that the dynamic password was changed since the config was set 171 | if should_read_from_file_system(): 172 | redis_username, redis_password = get_username_and_password_from_file_system() 173 | if not redis_password: 174 | raise Exception("Missing password from file system.") 175 | else: 176 | app.config["REDIS_PASSWORD"] = redis_password 177 | app.config["REDIS_USERNAME"] = redis_username 178 | 179 | 180 | def get_conn(): 181 | if app.config['USE_SENTINEL']: 182 | return _get_sentinel_conn() 183 | else: 184 | return _get_service_conn() 185 | 186 | 187 | def _get_service_conn(): 188 | connection_args = _get_connection_args(app.config["DB_SERVICE_HOST"], app.config["DB_SERVICE_PORT"]) 189 | return redis.Redis(**connection_args) 190 | 191 | 192 | def _get_connection_args(host: str, port:str) -> dict: 193 | connection_args = { 194 | "host": host, 195 | "port": port, 196 | "password": app.config['REDIS_PASSWORD'], 197 | "decode_responses": True 198 | } 199 | redis_username = app.config['REDIS_USERNAME'] 200 | if redis_username: 201 | # if no user name is sent, Redis will use the default username. 202 | connection_args['username'] = redis_username 203 | 204 | if app.config['SSL_ENABLED']: 205 | ssl_cert_reqs = "none" if app.config['SKIP_HOSTNAME_VALIDATION'] else 'required' 206 | connection_args['ssl'] = True 207 | connection_args['ssl_cert_reqs'] = ssl_cert_reqs 208 | 209 | return connection_args 210 | 211 | def _get_sentinel_conn(): 212 | # it would be nice to call sentinel.master_for redis-py API here. But this does not work when the bdb is configured 213 | # with TLS creating the connection directly instead 214 | 215 | master_info = get_master(app.config['REDIS_URL']) 216 | connection_args = _get_connection_args(str(master_info[0]), str(master_info[1])) 217 | return redis.Redis(**connection_args) 218 | 219 | 220 | def get_master(url): 221 | if not url.startswith('redis+sentinel://'): 222 | abort(406, "not supported") 223 | result = redis_sentinel_url.parse_sentinel_url(url) 224 | return sentinel.discover_master(result.default_client.service) 225 | 226 | 227 | def update_memtier_message(): 228 | while True: 229 | output = capp.memtier_process.stdout.readline() 230 | if output == '': 231 | return 232 | if output: 233 | capp.memtier_message = capp.memtier_message + "\n" + output.strip() 234 | 235 | def is_memtier_running(check_alive=True): 236 | if not hasattr(capp, 'memtier_process') or not capp.memtier_process: 237 | return False 238 | if check_alive and not capp.memtier_process.isAlive(): 239 | return False 240 | return True 241 | 242 | 243 | @app.route('/memtier_benchmark/start', methods=['POST']) 244 | def start_memtier_benchmark(): 245 | if is_memtier_running(): 246 | return jsonify({ 247 | 'response': "Memtier is running, can't run a new process", 248 | 'success': False 249 | }) 250 | req = request.get_json() or {} 251 | config = req.get("args", "") 252 | master_info = get_master(app.config['REDIS_URL']) 253 | master_ip = str(master_info[0]) 254 | master_port = str(master_info[1]) 255 | thread = MemtierThread(master_ip, master_port, app.config['REDIS_PASSWORD'], config) 256 | thread.start() 257 | capp.memtier_process = thread 258 | time.sleep(10) 259 | returncode = thread.return_code 260 | return jsonify({ 261 | 'response': capp.memtier_process.output, 262 | 'success': not returncode 263 | }) 264 | 265 | 266 | @app.route('/memtier_benchmark/poll', methods=['GET']) 267 | def poll_memtier_benchmark(): 268 | if not is_memtier_running(False): 269 | return jsonify({ 270 | 'response': (True, "Memtier is not running, can't poll it"), 271 | 'success': False 272 | }) 273 | returncode = capp.memtier_process.return_code 274 | message = capp.memtier_process.output 275 | if returncode is not None: 276 | capp.memtier_process = None 277 | return jsonify({ 278 | 'response': (returncode != None, message), 279 | 'success': not returncode 280 | }) 281 | 282 | 283 | @app.route('/memtier_benchmark/stop', methods=['POST']) 284 | def stop_memtier_benchmark(): 285 | if not is_memtier_running(): 286 | return jsonify({ 287 | 'response': "Memtier is not running, can't kill it", 288 | 'success': False 289 | }) 290 | capp.memtier_process.kill() 291 | message = capp.memtier_process.output 292 | capp.memtier_process = None 293 | return jsonify({ 294 | 'response': message, 295 | 'success': True 296 | }) 297 | 298 | 299 | 300 | @app.route('/masters', methods=['GET']) 301 | def masters(): 302 | success = False 303 | try: 304 | response = get_master(app.config['REDIS_URL']) 305 | success = True 306 | except Exception as err: 307 | response = 'Exception: %s' % str(err) 308 | return jsonify({ 309 | 'response': response, 310 | 'success': success 311 | }) 312 | 313 | 314 | def get_conn_info(url): 315 | conn_info = [] 316 | if url.startswith('redis://'): 317 | urlparts = urlparse(url) 318 | netloc = urlparts[1].partition(':') 319 | conn_info = [ 320 | ('Address', netloc[0]), 321 | ('Port', (netloc[2] or '6379')) 322 | ] 323 | elif url.startswith('redis+sentinel://'): 324 | result = redis_sentinel_url.parse_sentinel_url(url) 325 | print(result.hosts) 326 | conn_info = [ 327 | ('Sentinel Hosts', ','.join(['%s:%s' % (pair[0], pair[1]) 328 | for pair in result.hosts])), 329 | ('Service', result.default_client.service) 330 | ] 331 | 332 | return conn_info 333 | 334 | 335 | @app.route('/') 336 | def index(): 337 | return render_template('index.html', config=app.config, 338 | conninfo=get_conn_info(app.config['REDIS_URL'])) 339 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 675 Mass Ave, Cambridge, MA 02139, USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | Appendix: How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 19yy 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) 19yy name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Library General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------