PyMongo connection pools with non-default Linux Network Namespaces


I have question regarding PyMongo connection pool/sockets and Linux Network Namespaces. I have an application that requires only the MongoDB connections to be created in a non-default Linux Network Namespace (e.g., ‘ip netns …’). The rest of the application needs to run and create other TCP/IP sockets in the default namespace. (Note that in this case Linux Network Namespaces are being used outside of the typical docker use case.)

I know that PyMongo creates threads and sockets under the covers as part of the connection pooling, server monitoring, etc. However, I don’t see an easy way to tell PyMongo to create sockets in a desired network namespace, since threads/sockets can be created on many of the PyMongo API calls.

For example, when creating a traditional socket in a custom network namespace, you could do something like the following using pyroute2.

from socket import socket
from pyroute2 import netns

netns.setns(my_netns)                    # Change to a custom network namespace
sock = socket(...)                            # Instantiate a socket
netns.setns("/proc/1/ns/net")         # Change back to the default namespace

I assume something like the following will not work given the way that PyMongo implementing connection pooling.

client = MongoClient(....)
# PyMongo API calls after this point need to make connections to MongoDB from the 'my_netns' namespace.

Is there any way to tell PyMongo to create sockets in a custom network namespace that wouldn’t require something like wrapping every pymongo API call with setns()?