Created
September 4, 2019 08:18
-
-
Save thestick613/3d3416db939b944c1f5535061e1af345 to your computer and use it in GitHub Desktop.
octopus load balancer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# pip install gevent | |
from gevent import monkey | |
monkey.patch_all() | |
import gevent | |
import requests | |
import random | |
bind_on_ip = "127.0.0.1" | |
bind_on_port = 8080 | |
multiplex_on = [{"host": "google.com", "port": 443, "proto": "https"}, {"host": "google.com", "port": 443, "proto": "https"}] | |
def proxy(path, method, post_data=None): | |
print("proxy to", path, method, post_data) | |
if method == "GET": | |
r = requests.get(path, allow_redirects=True) | |
elif method == "HEAD": | |
r = requests.head(path, allow_redirects=True) | |
elif method == "POST": | |
r = requests.post(path, allow_redirects=True, data=post_data) | |
return r | |
def application(env, start_response): | |
method = env['REQUEST_METHOD'] | |
http_host = env['HTTP_HOST'] | |
try: | |
post_data = env['wsgi.input'].read() | |
except: | |
post_data = None | |
threads = [] | |
for dst in multiplex_on: | |
path = "%s://%s:%d/" % (dst["proto"], dst["host"], dst["port"]) | |
if env['PATH_INFO']: | |
path += env['PATH_INFO'] | |
if env['QUERY_STRING']: | |
path += '?' + env['QUERY_STRING'] | |
path = path.lstrip('/') | |
threads.append(gevent.spawn(proxy, path, method)) | |
if threads: | |
gevent.joinall(threads) | |
response = random.choice(threads).get() | |
start_response("%s %s" % (response.status_code, response.reason), response.headers.items()) | |
return [response.content] | |
if __name__ == "__main__": | |
import gevent.pywsgi as pywsgi | |
server = pywsgi.WSGIServer((bind_on_ip, bind_on_port), application=application, backlog=10000, log=None) | |
server.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment