Reputation: 9429
I am trying to build a reverse proxy (with twisted). The reverse proxy listens on ports 6000-6099 and should map those ports to different internal IP addresses. Once a connection is made to a port, it should do some pre-checks, like starting a virtual machine in a cluster.
Example:
PublicIP:6000 -> do pre-check -> forward traffic to InternalIP-1:6800
PublicIP:6001 -> do pre-check -> forward traffic to InternalIP-2:6800
...
I modified an example I found here (section 'Proxies and reverse proxies'). But I can't get it to work. Can anybody help?
from twisted.web import proxy, http
from twisted.internet import reactor
from twisted.python import log
import sys
log.startLogging(sys.stdout)
machines = {}
class ProxyFactory(http.HTTPFactory):
protocol = proxy.ReverseProxy
def connectionMade(self):
if not machines.has_key(self.request.port): # self.request.port?!
# start new machine in cluster
# machines[self.request.port] = new_machine_ip
# reverse proxy to machines[self.request.port] on port 6800
# return proxy.ReverseProxyResource(machines[self.request.port], 6800, '/')
for port in range(6000,6100):
reactor.listenTCP(port, ProxyFactory())
reactor.run()
Edit:
Upvotes: 2
Views: 928
Reputation: 10257
Twisted actually has a built in ReverseProxyResource
for this purpose, where the request object is passed to the render
method. It can be extended and modified to do the dynamic routing as you like.
https://twistedmatrix.com/documents/current/api/twisted.web.proxy.ReverseProxyResource.html
The simplest example is here, though you are free to override the resource methods to do the kind of checking you describe.
Site
in this example is a factory that is using the regular HTTP protocol.
Upvotes: 2