Connecting to a remote Python Bridge instance

Normally, the Python Bridge automatically starts and uses a local Python process running the gtoolkit_bridge code, installing it if necessary. We already saw that there are other PythonBridge options.

Building on those options, it is also possible to connect to a remote Python Bridge instance, i.e. one running on a remote server.

Security warning

The gtoolkit_bridge socket server code basically allows a client to control a Python program over a network connection, doing anything at all, reading and writing files and executing arbitrary code. Obviously this is a security risk.

For this reason, the socket server by default only allows connections coming from the local network, which means both the client and the server need to be on the same machine. This mitigates the security risk.

We will now be using the special --bind-any-interface command line option which opens the socket server to connections coming from anyone on the network. Do not use this in a production environment. This feature is for demonstration purposes only.

Starting the remote instance

On the remote server, install the necessary code and start the Python Bridge manually.

pipenv install gtoolkit_bridge

Pick an unused port, 9876 in this example, and start with the extra --bind-any-interface command line option.

pipenv run python -m gtoolkit_bridge --port 9876 --pharo 0 --method=msgpack --log --bind-any-interface

You should see some terminal output confirming a successful start.

PythonBridge starting {'port': '9876', 'pharo': '0', 'method': 'msgpack', 'log': True, 'bind_any_interface': True} PythonBridge ready PYTHON: Start consuming commands HANDLER (MsgPackSocketPlatform): loop func

Connecting to the remote instance

Now configure the platform to use a manual process and set the debug and remote server address, using your server name or IP address and the chosen port, before starting it.

PBPlatform current setManualProcess
  
myPythonBridge := PBApplication new.
myPythonBridge debugMode: true.
myPythonBridge settings
	serverSocketAddress: (LanguageLinkSocketAddress ipOrName: 'my-remote-server' port: 9876)
  

Now we can start the Python Bridge.

myPythonBridge start
  

Let's see what Python reports about the node/host it runs on.

myPythonBridge newCommandFactory
	<< #platform asP3GI import;
	<< (#platform asP3GI => #node) call;
	sendAndWait
  

When you adopt our instance as the one being used by Python snippets, regular Python snippets will also work as expected.

PBApplication uniqueInstance: myPythonBridge
  
import platform
platform.node()
  

Not all Python Bridge functionality is available, since the Python executable is remote and not directly accessible, which is necessary for some operations.

To clean up after this experiment, stop the Python Bridge and reset the platform.

myPythonBridge stop
  
PBPlatform reset