Introduction
In this article, the use of a Unix Domain Socket (UDS) in a Python shell job is described.
A UDS appears on Unix/Linux systems as a file in the filesystem, typically using an extension such as '<file-name>.sock'. Communication takes place entirely within the kernel and relies on mechanisms of Inter-Process Communication (IPC).
Because no network stack such as HTTP, gRPC, or TCP is involved, communication is extremely fast and remains confined to the local system, which also increases security.
A UDS can also be used in container environments such as Docker, OpenShift, or Kubernetes, as long as the container and the host share the same kernel. If the socket file is mounted through a volume, processes inside the container and on the host can access the same UDS.
Example
For details on how to invoke Python from shell jobs see the JS7 - How to run Python scripts from jobs article.
The following example demonstrates how to integrate a simple UDS server and client into a JS7 Python shell job:
#!/usr/bin/python3
import socket
import os
import json
# Defines the socket file path
socket_path = "/tmp/example.sock"
# Removes the socket file if it exists from a previous session
if os.path.exists(socket_path):
os.remove(socket_path)
# Configures the server
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(socket_path)
server.listen(1) # Allows 1 pending connection
print(f"UDS server listening on: {socket_path}")
server_is_running = True
# Starts the listener
while server_is_running:
conn, _ = server.accept()
data = conn.recv(1024)
if not data:
conn.close()
continue
print("server received:", data.decode("utf-8"))
# Sends the response to the client
response = json.dumps({"message": "hello client!"})
conn.sendall(response.encode("utf-8"))
# Closes the connection
conn.close()
# Stops the server
server_is_running = False
#!/usr/bin/python3
import json
import socket
# Defines the socket file path
socket_path = "/tmp/example.sock"
# Starts the connection
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect(socket_path)
# Sends the request to the server
request = json.dumps({"message": "hello server!"})
client.sendall(request.encode("utf-8"))
# Prints the server response
response = client.recv(1024)
print("client received:", response.decode("utf-8"))
# Closes the connection
client.close()
Resources
Downloads
- Simple Workflow Example for a Python UDS Shell Job (upload .json): pdPythonUDSShellJobExample.workflow.json