Tuesday, August 4, 2015

How to build a replicated ehcache through firewall and not to die trying

It's assumed that:

  • You already have a java application and you have an ehcache instance running in your program with 1 cache configured to replicate.
  • You want to connect 1 instance to another instance you have in a remote machine
  • The remote machine you are connecting to is located behind a firewall.
  • You have been given access to only 1 port to make an ssh connection to the remote (firewalled) machine.
Ehcache uses RMI to connect the remote instances. When the cache in host 1 tries to connect to cache in host 2, RMI opens a new server socket in host 1 to listen for incoming connections from the host 2.
The problem here is that these random ports are not accesible to remote hosts because the hosts are behind a firewall.

So to fix it, we need to configure ehcache to only use 2 ports. The "remoteObjectPort" does the magic. So we have this ehcache.xml configuration:
  • 1 server port for the ehcache server to listen to other ehcache servers.
  • 1 server port for the ehcache cache to listen to incoming connections (this cache is the actual map in memory that is being replicated).
And the related properties are these. Inject it with System.setProperties(ehcacheProperties) before loading the ehcache instance in your program.
Open the 4 tunnels to the remote machine:

  • 1 local port for the ehcache server to listen to incoming connections from remote cache server
  • 1 local port for the ehcache cache for incoming connections from the remote cache
  • 1 remote port for remote ehcache server to listen incoming connections from our local host
  • 1 remote port for remote ehcache cache to listen to incoming connections from our local host

Run java programs on both machines (local and remote) with the "java.rmi.server.hostname" so the RMI server reports to the other RMI (the remote one) that it's address is "127.0.0.1" rather than any other IP it may has; so the tunnels can work. If you have any comment or suggestion please contact me.